circuitbuild.c 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  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. static double
  895. pathbias_get_disable_rate(const or_options_t *options)
  896. {
  897. // XXX: This needs tuning based on use + experimentation before we set it
  898. #define DFLT_PATH_BIAS_DISABLE_PCT 0
  899. if (options->PathBiasDisableRate >= 0.0)
  900. return options->PathBiasDisableRate;
  901. else
  902. return networkstatus_get_param(NULL, "pb_disablepct",
  903. DFLT_PATH_BIAS_DISABLE_PCT, 0, 100)/100.0;
  904. }
  905. static int
  906. pathbias_get_scale_threshold(const or_options_t *options)
  907. {
  908. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 200
  909. if (options->PathBiasScaleThreshold >= 2)
  910. return options->PathBiasScaleThreshold;
  911. else
  912. return networkstatus_get_param(NULL, "pb_scalecircs",
  913. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  914. INT32_MAX);
  915. }
  916. static int
  917. pathbias_get_scale_factor(const or_options_t *options)
  918. {
  919. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  920. if (options->PathBiasScaleFactor >= 1)
  921. return options->PathBiasScaleFactor;
  922. else
  923. return networkstatus_get_param(NULL, "pb_scalefactor",
  924. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  925. }
  926. static const char *
  927. pathbias_state_to_string(path_state_t state)
  928. {
  929. switch (state) {
  930. case PATH_STATE_NEW_CIRC:
  931. return "new";
  932. case PATH_STATE_DID_FIRST_HOP:
  933. return "first hop";
  934. case PATH_STATE_SUCCEEDED:
  935. return "succeeded";
  936. }
  937. return "unknown";
  938. }
  939. /**
  940. * Check our circuit state to see if this is a successful first hop.
  941. * If so, record it in the current guard's path bias first_hop count.
  942. *
  943. * Also check for several potential error cases for bug #6475.
  944. */
  945. static int
  946. pathbias_count_first_hop(origin_circuit_t *circ)
  947. {
  948. #define FIRST_HOP_NOTICE_INTERVAL (600)
  949. static ratelim_t first_hop_notice_limit =
  950. RATELIM_INIT(FIRST_HOP_NOTICE_INTERVAL);
  951. char *rate_msg = NULL;
  952. /* We can't do path bias accounting without entry guards.
  953. * Testing and controller circuits also have no guards. */
  954. if (get_options()->UseEntryGuards == 0 ||
  955. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  956. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) {
  957. return 0;
  958. }
  959. /* Completely ignore one hop circuits */
  960. if (circ->build_state->onehop_tunnel ||
  961. circ->build_state->desired_path_len == 1) {
  962. /* Check for inconsistency */
  963. if (circ->build_state->desired_path_len != 1 ||
  964. !circ->build_state->onehop_tunnel) {
  965. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  966. approx_time()))) {
  967. log_notice(LD_BUG,
  968. "One-hop circuit has length %d. Path state is %s. "
  969. "Circuit is a %s currently %s.%s",
  970. circ->build_state->desired_path_len,
  971. pathbias_state_to_string(circ->path_state),
  972. circuit_purpose_to_string(circ->base_.purpose),
  973. circuit_state_to_string(circ->base_.state),
  974. rate_msg);
  975. tor_free(rate_msg);
  976. }
  977. tor_fragile_assert();
  978. }
  979. return 0;
  980. }
  981. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  982. /* Help track down the real cause of bug #6475: */
  983. if (circ->has_opened && circ->path_state != PATH_STATE_DID_FIRST_HOP) {
  984. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  985. approx_time()))) {
  986. log_info(LD_BUG,
  987. "Opened circuit is in strange path state %s. "
  988. "Circuit is a %s currently %s.%s",
  989. pathbias_state_to_string(circ->path_state),
  990. circuit_purpose_to_string(circ->base_.purpose),
  991. circuit_state_to_string(circ->base_.state),
  992. rate_msg);
  993. tor_free(rate_msg);
  994. }
  995. }
  996. /* Don't count cannibalized circs for path bias */
  997. if (!circ->has_opened) {
  998. entry_guard_t *guard;
  999. guard =
  1000. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1001. if (guard) {
  1002. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1003. circ->path_state = PATH_STATE_DID_FIRST_HOP;
  1004. if (entry_guard_inc_first_hop_count(guard) < 0) {
  1005. /* Bogus guard; we already warned. */
  1006. return -END_CIRC_REASON_TORPROTOCOL;
  1007. }
  1008. } else {
  1009. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1010. approx_time()))) {
  1011. log_info(LD_BUG,
  1012. "Unopened circuit has strange path state %s. "
  1013. "Circuit is a %s currently %s.%s",
  1014. pathbias_state_to_string(circ->path_state),
  1015. circuit_purpose_to_string(circ->base_.purpose),
  1016. circuit_state_to_string(circ->base_.state),
  1017. rate_msg);
  1018. tor_free(rate_msg);
  1019. }
  1020. }
  1021. } else {
  1022. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1023. approx_time()))) {
  1024. log_info(LD_BUG,
  1025. "Unopened circuit has no known guard. "
  1026. "Circuit is a %s currently %s.%s",
  1027. circuit_purpose_to_string(circ->base_.purpose),
  1028. circuit_state_to_string(circ->base_.state),
  1029. rate_msg);
  1030. tor_free(rate_msg);
  1031. }
  1032. }
  1033. }
  1034. } else {
  1035. /* Help track down the real cause of bug #6475: */
  1036. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1037. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1038. approx_time()))) {
  1039. log_info(LD_BUG,
  1040. "A %s circuit is in cpath state %d (opened: %d). "
  1041. "Circuit is a %s currently %s.%s",
  1042. pathbias_state_to_string(circ->path_state),
  1043. circ->cpath->state, circ->has_opened,
  1044. circuit_purpose_to_string(circ->base_.purpose),
  1045. circuit_state_to_string(circ->base_.state),
  1046. rate_msg);
  1047. tor_free(rate_msg);
  1048. }
  1049. }
  1050. }
  1051. return 0;
  1052. }
  1053. /**
  1054. * Check our circuit state to see if this is a successful circuit
  1055. * completion. If so, record it in the current guard's path bias
  1056. * success count.
  1057. *
  1058. * Also check for several potential error cases for bug #6475.
  1059. */
  1060. static void
  1061. pathbias_count_success(origin_circuit_t *circ)
  1062. {
  1063. #define SUCCESS_NOTICE_INTERVAL (600)
  1064. static ratelim_t success_notice_limit =
  1065. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1066. char *rate_msg = NULL;
  1067. entry_guard_t *guard = NULL;
  1068. /* We can't do path bias accounting without entry guards.
  1069. * Testing and controller circuits also have no guards. */
  1070. if (get_options()->UseEntryGuards == 0 ||
  1071. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1072. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) {
  1073. return;
  1074. }
  1075. /* Ignore one hop circuits */
  1076. if (circ->build_state->onehop_tunnel ||
  1077. circ->build_state->desired_path_len == 1) {
  1078. /* Check for consistency */
  1079. if (circ->build_state->desired_path_len != 1 ||
  1080. !circ->build_state->onehop_tunnel) {
  1081. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1082. approx_time()))) {
  1083. log_notice(LD_BUG,
  1084. "One-hop circuit has length %d. Path state is %s. "
  1085. "Circuit is a %s currently %s.%s",
  1086. circ->build_state->desired_path_len,
  1087. pathbias_state_to_string(circ->path_state),
  1088. circuit_purpose_to_string(circ->base_.purpose),
  1089. circuit_state_to_string(circ->base_.state),
  1090. rate_msg);
  1091. tor_free(rate_msg);
  1092. }
  1093. tor_fragile_assert();
  1094. }
  1095. return;
  1096. }
  1097. /* Don't count cannibalized/reused circs for path bias */
  1098. if (!circ->has_opened) {
  1099. guard =
  1100. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1101. if (guard) {
  1102. if (circ->path_state == PATH_STATE_DID_FIRST_HOP) {
  1103. circ->path_state = PATH_STATE_SUCCEEDED;
  1104. guard->circuit_successes++;
  1105. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
  1106. guard->circuit_successes, guard->first_hops,
  1107. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1108. } else {
  1109. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1110. approx_time()))) {
  1111. log_info(LD_BUG,
  1112. "Succeeded circuit is in strange path state %s. "
  1113. "Circuit is a %s currently %s.%s",
  1114. pathbias_state_to_string(circ->path_state),
  1115. circuit_purpose_to_string(circ->base_.purpose),
  1116. circuit_state_to_string(circ->base_.state),
  1117. rate_msg);
  1118. tor_free(rate_msg);
  1119. }
  1120. }
  1121. if (guard->first_hops < guard->circuit_successes) {
  1122. log_notice(LD_BUG, "Unexpectedly high circuit_successes (%u/%u) "
  1123. "for guard %s=%s",
  1124. guard->circuit_successes, guard->first_hops,
  1125. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1126. }
  1127. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1128. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1129. * No need to log that case. */
  1130. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1131. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1132. approx_time()))) {
  1133. log_info(LD_BUG,
  1134. "Completed circuit has no known guard. "
  1135. "Circuit is a %s currently %s.%s",
  1136. circuit_purpose_to_string(circ->base_.purpose),
  1137. circuit_state_to_string(circ->base_.state),
  1138. rate_msg);
  1139. tor_free(rate_msg);
  1140. }
  1141. }
  1142. } else {
  1143. if (circ->path_state != PATH_STATE_SUCCEEDED) {
  1144. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1145. approx_time()))) {
  1146. log_info(LD_BUG,
  1147. "Opened circuit is in strange path state %s. "
  1148. "Circuit is a %s currently %s.%s",
  1149. pathbias_state_to_string(circ->path_state),
  1150. circuit_purpose_to_string(circ->base_.purpose),
  1151. circuit_state_to_string(circ->base_.state),
  1152. rate_msg);
  1153. tor_free(rate_msg);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /** Increment the number of times we successfully extended a circuit to
  1159. * 'guard', first checking if the failure rate is high enough that we should
  1160. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  1161. * guard looks fine. */
  1162. static int
  1163. entry_guard_inc_first_hop_count(entry_guard_t *guard)
  1164. {
  1165. const or_options_t *options = get_options();
  1166. entry_guards_changed();
  1167. if (guard->first_hops > (unsigned)pathbias_get_min_circs(options)) {
  1168. /* Note: We rely on the < comparison here to allow us to set a 0
  1169. * rate and disable the feature entirely. If refactoring, don't
  1170. * change to <= */
  1171. if (guard->circuit_successes/((double)guard->first_hops)
  1172. < pathbias_get_disable_rate(options)) {
  1173. /* This message is currently disabled by default. */
  1174. log_warn(LD_PROTOCOL,
  1175. "Extremely low circuit success rate %u/%u for guard %s=%s. "
  1176. "This indicates either an overloaded guard, an attack, or "
  1177. "a bug.",
  1178. guard->circuit_successes, guard->first_hops, guard->nickname,
  1179. hex_str(guard->identity, DIGEST_LEN));
  1180. guard->path_bias_disabled = 1;
  1181. guard->bad_since = approx_time();
  1182. return -1;
  1183. } else if (guard->circuit_successes/((double)guard->first_hops)
  1184. < pathbias_get_notice_rate(options)
  1185. && !guard->path_bias_notice) {
  1186. guard->path_bias_notice = 1;
  1187. log_notice(LD_PROTOCOL,
  1188. "Low circuit success rate %u/%u for guard %s=%s.",
  1189. guard->circuit_successes, guard->first_hops, guard->nickname,
  1190. hex_str(guard->identity, DIGEST_LEN));
  1191. }
  1192. }
  1193. /* If we get a ton of circuits, just scale everything down */
  1194. if (guard->first_hops > (unsigned)pathbias_get_scale_threshold(options)) {
  1195. const int scale_factor = pathbias_get_scale_factor(options);
  1196. /* For now, only scale if there will be no rounding error...
  1197. * XXX024: We want to switch to a real moving average for 0.2.4. */
  1198. if ((guard->first_hops % scale_factor) == 0 &&
  1199. (guard->circuit_successes % scale_factor) == 0) {
  1200. log_info(LD_PROTOCOL,
  1201. "Scaling pathbias counts to (%u/%u)/%d for guard %s=%s",
  1202. guard->circuit_successes, guard->first_hops,
  1203. scale_factor, guard->nickname, hex_str(guard->identity,
  1204. DIGEST_LEN));
  1205. guard->first_hops /= scale_factor;
  1206. guard->circuit_successes /= scale_factor;
  1207. }
  1208. }
  1209. guard->first_hops++;
  1210. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
  1211. guard->circuit_successes, guard->first_hops, guard->nickname,
  1212. hex_str(guard->identity, DIGEST_LEN));
  1213. return 0;
  1214. }
  1215. /** A created or extended cell came back to us on the circuit, and it included
  1216. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  1217. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  1218. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  1219. *
  1220. * Calculate the appropriate keys and digests, make sure KH is
  1221. * correct, and initialize this hop of the cpath.
  1222. *
  1223. * Return - reason if we want to mark circ for close, else return 0.
  1224. */
  1225. int
  1226. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  1227. const uint8_t *reply)
  1228. {
  1229. char keys[CPATH_KEY_MATERIAL_LEN];
  1230. crypt_path_t *hop;
  1231. int rv;
  1232. if ((rv = pathbias_count_first_hop(circ)) < 0)
  1233. return rv;
  1234. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1235. hop = circ->cpath;
  1236. } else {
  1237. hop = onion_next_hop_in_cpath(circ->cpath);
  1238. if (!hop) { /* got an extended when we're all done? */
  1239. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1240. return - END_CIRC_REASON_TORPROTOCOL;
  1241. }
  1242. }
  1243. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1244. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  1245. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  1246. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1247. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1248. return -END_CIRC_REASON_TORPROTOCOL;
  1249. }
  1250. /* Remember hash of g^xy */
  1251. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  1252. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  1253. if (fast_client_handshake(hop->fast_handshake_state, reply,
  1254. (uint8_t*)keys,
  1255. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1256. log_warn(LD_CIRC,"fast_client_handshake failed.");
  1257. return -END_CIRC_REASON_TORPROTOCOL;
  1258. }
  1259. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  1260. } else {
  1261. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  1262. return -END_CIRC_REASON_TORPROTOCOL;
  1263. }
  1264. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  1265. hop->dh_handshake_state = NULL;
  1266. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  1267. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1268. return -END_CIRC_REASON_TORPROTOCOL;
  1269. }
  1270. hop->state = CPATH_STATE_OPEN;
  1271. log_info(LD_CIRC,"Finished building %scircuit hop:",
  1272. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  1273. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1274. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1275. return 0;
  1276. }
  1277. /** We received a relay truncated cell on circ.
  1278. *
  1279. * Since we don't ask for truncates currently, getting a truncated
  1280. * means that a connection broke or an extend failed. For now,
  1281. * just give up: for circ to close, and return 0.
  1282. */
  1283. int
  1284. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1285. {
  1286. // crypt_path_t *victim;
  1287. // connection_t *stream;
  1288. tor_assert(circ);
  1289. tor_assert(layer);
  1290. /* XXX Since we don't ask for truncates currently, getting a truncated
  1291. * means that a connection broke or an extend failed. For now,
  1292. * just give up.
  1293. */
  1294. circuit_mark_for_close(TO_CIRCUIT(circ),
  1295. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_CHANNEL_CLOSED|reason);
  1296. return 0;
  1297. #if 0
  1298. while (layer->next != circ->cpath) {
  1299. /* we need to clear out layer->next */
  1300. victim = layer->next;
  1301. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1302. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1303. if (stream->cpath_layer == victim) {
  1304. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1305. stream->stream_id);
  1306. /* no need to send 'end' relay cells,
  1307. * because the other side's already dead
  1308. */
  1309. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1310. }
  1311. }
  1312. layer->next = victim->next;
  1313. circuit_free_cpath_node(victim);
  1314. }
  1315. log_info(LD_CIRC, "finished");
  1316. return 0;
  1317. #endif
  1318. }
  1319. /** Given a response payload and keys, initialize, then send a created
  1320. * cell back.
  1321. */
  1322. int
  1323. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  1324. const char *keys)
  1325. {
  1326. cell_t cell;
  1327. crypt_path_t *tmp_cpath;
  1328. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1329. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1330. memset(&cell, 0, sizeof(cell_t));
  1331. cell.command = cell_type;
  1332. cell.circ_id = circ->p_circ_id;
  1333. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1334. memcpy(cell.payload, payload,
  1335. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  1336. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1337. (unsigned int)get_uint32(keys),
  1338. (unsigned int)get_uint32(keys+20));
  1339. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1340. log_warn(LD_BUG,"Circuit initialization failed");
  1341. tor_free(tmp_cpath);
  1342. return -1;
  1343. }
  1344. circ->n_digest = tmp_cpath->f_digest;
  1345. circ->n_crypto = tmp_cpath->f_crypto;
  1346. circ->p_digest = tmp_cpath->b_digest;
  1347. circ->p_crypto = tmp_cpath->b_crypto;
  1348. tmp_cpath->magic = 0;
  1349. tor_free(tmp_cpath);
  1350. if (cell_type == CELL_CREATED)
  1351. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  1352. else
  1353. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  1354. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  1355. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1356. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1357. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1358. circ->is_first_hop ? "created_fast" : "created");
  1359. if (!channel_is_local(circ->p_chan) &&
  1360. !channel_is_outgoing(circ->p_chan)) {
  1361. /* record that we could process create cells from a non-local conn
  1362. * that we didn't initiate; presumably this means that create cells
  1363. * can reach us too. */
  1364. router_orport_found_reachable();
  1365. }
  1366. return 0;
  1367. }
  1368. /** Choose a length for a circuit of purpose <b>purpose</b>.
  1369. * Default length is 3 + the number of endpoints that would give something
  1370. * away. If the routerlist <b>routers</b> doesn't have enough routers
  1371. * to handle the desired path length, return as large a path length as
  1372. * is feasible, except if it's less than 2, in which case return -1.
  1373. */
  1374. static int
  1375. new_route_len(uint8_t purpose, extend_info_t *exit,
  1376. smartlist_t *nodes)
  1377. {
  1378. int num_acceptable_routers;
  1379. int routelen;
  1380. tor_assert(nodes);
  1381. routelen = DEFAULT_ROUTE_LEN;
  1382. if (exit &&
  1383. purpose != CIRCUIT_PURPOSE_TESTING &&
  1384. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1385. routelen++;
  1386. num_acceptable_routers = count_acceptable_nodes(nodes);
  1387. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1388. routelen, num_acceptable_routers, smartlist_len(nodes));
  1389. if (num_acceptable_routers < 2) {
  1390. log_info(LD_CIRC,
  1391. "Not enough acceptable routers (%d). Discarding this circuit.",
  1392. num_acceptable_routers);
  1393. return -1;
  1394. }
  1395. if (num_acceptable_routers < routelen) {
  1396. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  1397. routelen, num_acceptable_routers);
  1398. routelen = num_acceptable_routers;
  1399. }
  1400. return routelen;
  1401. }
  1402. /** Return a newly allocated list of uint16_t * for each predicted port not
  1403. * handled by a current circuit. */
  1404. static smartlist_t *
  1405. circuit_get_unhandled_ports(time_t now)
  1406. {
  1407. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1408. circuit_remove_handled_ports(dest);
  1409. return dest;
  1410. }
  1411. /** Return 1 if we already have circuits present or on the way for
  1412. * all anticipated ports. Return 0 if we should make more.
  1413. *
  1414. * If we're returning 0, set need_uptime and need_capacity to
  1415. * indicate any requirements that the unhandled ports have.
  1416. */
  1417. int
  1418. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1419. int *need_capacity)
  1420. {
  1421. int i, enough;
  1422. uint16_t *port;
  1423. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1424. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1425. tor_assert(need_uptime);
  1426. tor_assert(need_capacity);
  1427. // Always predict need_capacity
  1428. *need_capacity = 1;
  1429. enough = (smartlist_len(sl) == 0);
  1430. for (i = 0; i < smartlist_len(sl); ++i) {
  1431. port = smartlist_get(sl, i);
  1432. if (smartlist_string_num_isin(LongLivedServices, *port))
  1433. *need_uptime = 1;
  1434. tor_free(port);
  1435. }
  1436. smartlist_free(sl);
  1437. return enough;
  1438. }
  1439. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1440. * <b>needed_ports</b>, else return 0.
  1441. */
  1442. static int
  1443. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1444. { /* XXXX MOVE */
  1445. int i;
  1446. uint16_t port;
  1447. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1448. addr_policy_result_t r;
  1449. /* alignment issues aren't a worry for this dereference, since
  1450. needed_ports is explicitly a smartlist of uint16_t's */
  1451. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1452. tor_assert(port);
  1453. if (node)
  1454. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1455. else
  1456. continue;
  1457. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1458. return 1;
  1459. }
  1460. return 0;
  1461. }
  1462. /** Return true iff <b>conn</b> needs another general circuit to be
  1463. * built. */
  1464. static int
  1465. ap_stream_wants_exit_attention(connection_t *conn)
  1466. {
  1467. entry_connection_t *entry;
  1468. if (conn->type != CONN_TYPE_AP)
  1469. return 0;
  1470. entry = TO_ENTRY_CONN(conn);
  1471. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1472. !conn->marked_for_close &&
  1473. !(entry->want_onehop) && /* ignore one-hop streams */
  1474. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1475. !(entry->chosen_exit_name) && /* ignore defined streams */
  1476. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1477. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1478. MIN_CIRCUITS_HANDLING_STREAM))
  1479. return 1;
  1480. return 0;
  1481. }
  1482. /** Return a pointer to a suitable router to be the exit node for the
  1483. * general-purpose circuit we're about to build.
  1484. *
  1485. * Look through the connection array, and choose a router that maximizes
  1486. * the number of pending streams that can exit from this router.
  1487. *
  1488. * Return NULL if we can't find any suitable routers.
  1489. */
  1490. static const node_t *
  1491. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1492. {
  1493. int *n_supported;
  1494. int n_pending_connections = 0;
  1495. smartlist_t *connections;
  1496. int best_support = -1;
  1497. int n_best_support=0;
  1498. const or_options_t *options = get_options();
  1499. const smartlist_t *the_nodes;
  1500. const node_t *node=NULL;
  1501. connections = get_connection_array();
  1502. /* Count how many connections are waiting for a circuit to be built.
  1503. * We use this for log messages now, but in the future we may depend on it.
  1504. */
  1505. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1506. {
  1507. if (ap_stream_wants_exit_attention(conn))
  1508. ++n_pending_connections;
  1509. });
  1510. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1511. // n_pending_connections);
  1512. /* Now we count, for each of the routers in the directory, how many
  1513. * of the pending connections could possibly exit from that
  1514. * router (n_supported[i]). (We can't be sure about cases where we
  1515. * don't know the IP address of the pending connection.)
  1516. *
  1517. * -1 means "Don't use this router at all."
  1518. */
  1519. the_nodes = nodelist_get_list();
  1520. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1521. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1522. const int i = node_sl_idx;
  1523. if (router_digest_is_me(node->identity)) {
  1524. n_supported[i] = -1;
  1525. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1526. /* XXX there's probably a reverse predecessor attack here, but
  1527. * it's slow. should we take this out? -RD
  1528. */
  1529. continue;
  1530. }
  1531. if (!node_has_descriptor(node)) {
  1532. n_supported[i] = -1;
  1533. continue;
  1534. }
  1535. if (!node->is_running || node->is_bad_exit) {
  1536. n_supported[i] = -1;
  1537. continue; /* skip routers that are known to be down or bad exits */
  1538. }
  1539. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1540. /* never pick a non-general node as a random exit. */
  1541. n_supported[i] = -1;
  1542. continue;
  1543. }
  1544. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1545. n_supported[i] = -1;
  1546. continue; /* user asked us not to use it, no matter what */
  1547. }
  1548. if (options->ExitNodes &&
  1549. !routerset_contains_node(options->ExitNodes, node)) {
  1550. n_supported[i] = -1;
  1551. continue; /* not one of our chosen exit nodes */
  1552. }
  1553. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1554. n_supported[i] = -1;
  1555. continue; /* skip routers that are not suitable. Don't worry if
  1556. * this makes us reject all the possible routers: if so,
  1557. * we'll retry later in this function with need_update and
  1558. * need_capacity set to 0. */
  1559. }
  1560. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1561. /* if it's invalid and we don't want it */
  1562. n_supported[i] = -1;
  1563. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1564. // router->nickname, i);
  1565. continue; /* skip invalid routers */
  1566. }
  1567. if (options->ExcludeSingleHopRelays &&
  1568. node_allows_single_hop_exits(node)) {
  1569. n_supported[i] = -1;
  1570. continue;
  1571. }
  1572. if (node_exit_policy_rejects_all(node)) {
  1573. n_supported[i] = -1;
  1574. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1575. // router->nickname, i);
  1576. continue; /* skip routers that reject all */
  1577. }
  1578. n_supported[i] = 0;
  1579. /* iterate over connections */
  1580. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1581. if (!ap_stream_wants_exit_attention(conn))
  1582. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1583. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1584. ++n_supported[i];
  1585. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1586. // router->nickname, i, n_supported[i]);
  1587. } else {
  1588. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1589. // router->nickname, i);
  1590. }
  1591. } SMARTLIST_FOREACH_END(conn);
  1592. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1593. /* Leave best_support at -1 if that's where it is, so we can
  1594. * distinguish it later. */
  1595. continue;
  1596. }
  1597. if (n_supported[i] > best_support) {
  1598. /* If this router is better than previous ones, remember its index
  1599. * and goodness, and start counting how many routers are this good. */
  1600. best_support = n_supported[i]; n_best_support=1;
  1601. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1602. // router->nickname);
  1603. } else if (n_supported[i] == best_support) {
  1604. /* If this router is _as good_ as the best one, just increment the
  1605. * count of equally good routers.*/
  1606. ++n_best_support;
  1607. }
  1608. } SMARTLIST_FOREACH_END(node);
  1609. log_info(LD_CIRC,
  1610. "Found %d servers that might support %d/%d pending connections.",
  1611. n_best_support, best_support >= 0 ? best_support : 0,
  1612. n_pending_connections);
  1613. /* If any routers definitely support any pending connections, choose one
  1614. * at random. */
  1615. if (best_support > 0) {
  1616. smartlist_t *supporting = smartlist_new();
  1617. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1618. if (n_supported[node_sl_idx] == best_support)
  1619. smartlist_add(supporting, (void*)node);
  1620. });
  1621. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1622. smartlist_free(supporting);
  1623. } else {
  1624. /* Either there are no pending connections, or no routers even seem to
  1625. * possibly support any of them. Choose a router at random that satisfies
  1626. * at least one predicted exit port. */
  1627. int attempt;
  1628. smartlist_t *needed_ports, *supporting;
  1629. if (best_support == -1) {
  1630. if (need_uptime || need_capacity) {
  1631. log_info(LD_CIRC,
  1632. "We couldn't find any live%s%s routers; falling back "
  1633. "to list of all routers.",
  1634. need_capacity?", fast":"",
  1635. need_uptime?", stable":"");
  1636. tor_free(n_supported);
  1637. return choose_good_exit_server_general(0, 0);
  1638. }
  1639. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1640. "choosing a doomed exit at random.",
  1641. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1642. }
  1643. supporting = smartlist_new();
  1644. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1645. for (attempt = 0; attempt < 2; attempt++) {
  1646. /* try once to pick only from routers that satisfy a needed port,
  1647. * then if there are none, pick from any that support exiting. */
  1648. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1649. if (n_supported[node_sl_idx] != -1 &&
  1650. (attempt || node_handles_some_port(node, needed_ports))) {
  1651. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1652. // try, router->nickname);
  1653. smartlist_add(supporting, (void*)node);
  1654. }
  1655. } SMARTLIST_FOREACH_END(node);
  1656. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1657. if (node)
  1658. break;
  1659. smartlist_clear(supporting);
  1660. /* If we reach this point, we can't actually support any unhandled
  1661. * predicted ports, so clear all the remaining ones. */
  1662. if (smartlist_len(needed_ports))
  1663. rep_hist_remove_predicted_ports(needed_ports);
  1664. }
  1665. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1666. smartlist_free(needed_ports);
  1667. smartlist_free(supporting);
  1668. }
  1669. tor_free(n_supported);
  1670. if (node) {
  1671. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1672. return node;
  1673. }
  1674. if (options->ExitNodes) {
  1675. log_warn(LD_CIRC,
  1676. "No specified %sexit routers seem to be running: "
  1677. "can't choose an exit.",
  1678. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1679. }
  1680. return NULL;
  1681. }
  1682. /** Return a pointer to a suitable router to be the exit node for the
  1683. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1684. * if no router is suitable).
  1685. *
  1686. * For general-purpose circuits, pass it off to
  1687. * choose_good_exit_server_general()
  1688. *
  1689. * For client-side rendezvous circuits, choose a random node, weighted
  1690. * toward the preferences in 'options'.
  1691. */
  1692. static const node_t *
  1693. choose_good_exit_server(uint8_t purpose,
  1694. int need_uptime, int need_capacity, int is_internal)
  1695. {
  1696. const or_options_t *options = get_options();
  1697. router_crn_flags_t flags = CRN_NEED_DESC;
  1698. if (need_uptime)
  1699. flags |= CRN_NEED_UPTIME;
  1700. if (need_capacity)
  1701. flags |= CRN_NEED_CAPACITY;
  1702. switch (purpose) {
  1703. case CIRCUIT_PURPOSE_C_GENERAL:
  1704. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1705. flags |= CRN_ALLOW_INVALID;
  1706. if (is_internal) /* pick it like a middle hop */
  1707. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1708. else
  1709. return choose_good_exit_server_general(need_uptime,need_capacity);
  1710. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1711. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1712. flags |= CRN_ALLOW_INVALID;
  1713. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1714. }
  1715. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1716. tor_fragile_assert();
  1717. return NULL;
  1718. }
  1719. /** Log a warning if the user specified an exit for the circuit that
  1720. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1721. static void
  1722. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1723. {
  1724. const or_options_t *options = get_options();
  1725. routerset_t *rs = options->ExcludeNodes;
  1726. const char *description;
  1727. uint8_t purpose = circ->base_.purpose;
  1728. if (circ->build_state->onehop_tunnel)
  1729. return;
  1730. switch (purpose)
  1731. {
  1732. default:
  1733. case CIRCUIT_PURPOSE_OR:
  1734. case CIRCUIT_PURPOSE_INTRO_POINT:
  1735. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1736. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1737. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1738. (int)purpose,
  1739. circuit_purpose_to_string(purpose));
  1740. return;
  1741. case CIRCUIT_PURPOSE_C_GENERAL:
  1742. if (circ->build_state->is_internal)
  1743. return;
  1744. description = "requested exit node";
  1745. rs = options->ExcludeExitNodesUnion_;
  1746. break;
  1747. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1748. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1749. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1750. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1751. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1752. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1753. case CIRCUIT_PURPOSE_TESTING:
  1754. return;
  1755. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1756. case CIRCUIT_PURPOSE_C_REND_READY:
  1757. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1758. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1759. description = "chosen rendezvous point";
  1760. break;
  1761. case CIRCUIT_PURPOSE_CONTROLLER:
  1762. rs = options->ExcludeExitNodesUnion_;
  1763. description = "controller-selected circuit target";
  1764. break;
  1765. }
  1766. if (routerset_contains_extendinfo(rs, exit)) {
  1767. /* We should never get here if StrictNodes is set to 1. */
  1768. if (options->StrictNodes) {
  1769. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1770. "even though StrictNodes is set. Please report. "
  1771. "(Circuit purpose: %s)",
  1772. description, extend_info_describe(exit),
  1773. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1774. circuit_purpose_to_string(purpose));
  1775. } else {
  1776. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1777. "ExcludeNodes%s, because no better options were available. To "
  1778. "prevent this (and possibly break your Tor functionality), "
  1779. "set the StrictNodes configuration option. "
  1780. "(Circuit purpose: %s)",
  1781. description, extend_info_describe(exit),
  1782. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1783. circuit_purpose_to_string(purpose));
  1784. }
  1785. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1786. }
  1787. return;
  1788. }
  1789. /** Decide a suitable length for circ's cpath, and pick an exit
  1790. * router (or use <b>exit</b> if provided). Store these in the
  1791. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1792. static int
  1793. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1794. {
  1795. cpath_build_state_t *state = circ->build_state;
  1796. if (state->onehop_tunnel) {
  1797. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1798. state->desired_path_len = 1;
  1799. } else {
  1800. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1801. if (r < 1) /* must be at least 1 */
  1802. return -1;
  1803. state->desired_path_len = r;
  1804. }
  1805. if (exit) { /* the circuit-builder pre-requested one */
  1806. warn_if_last_router_excluded(circ, exit);
  1807. log_info(LD_CIRC,"Using requested exit node '%s'",
  1808. extend_info_describe(exit));
  1809. exit = extend_info_dup(exit);
  1810. } else { /* we have to decide one */
  1811. const node_t *node =
  1812. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1813. state->need_capacity, state->is_internal);
  1814. if (!node) {
  1815. log_warn(LD_CIRC,"failed to choose an exit server");
  1816. return -1;
  1817. }
  1818. exit = extend_info_from_node(node, 0);
  1819. tor_assert(exit);
  1820. }
  1821. state->chosen_exit = exit;
  1822. return 0;
  1823. }
  1824. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1825. * hop to the cpath reflecting this. Don't send the next extend cell --
  1826. * the caller will do this if it wants to.
  1827. */
  1828. int
  1829. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1830. {
  1831. cpath_build_state_t *state;
  1832. tor_assert(exit);
  1833. tor_assert(circ);
  1834. state = circ->build_state;
  1835. tor_assert(state);
  1836. extend_info_free(state->chosen_exit);
  1837. state->chosen_exit = extend_info_dup(exit);
  1838. ++circ->build_state->desired_path_len;
  1839. onion_append_hop(&circ->cpath, exit);
  1840. return 0;
  1841. }
  1842. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1843. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1844. * send the next extend cell to begin connecting to that hop.
  1845. */
  1846. int
  1847. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1848. {
  1849. int err_reason = 0;
  1850. warn_if_last_router_excluded(circ, exit);
  1851. circuit_append_new_exit(circ, exit);
  1852. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1853. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1854. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1855. extend_info_describe(exit));
  1856. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1857. return -1;
  1858. }
  1859. return 0;
  1860. }
  1861. /** Return the number of routers in <b>routers</b> that are currently up
  1862. * and available for building circuits through.
  1863. */
  1864. static int
  1865. count_acceptable_nodes(smartlist_t *nodes)
  1866. {
  1867. int num=0;
  1868. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1869. // log_debug(LD_CIRC,
  1870. // "Contemplating whether router %d (%s) is a new option.",
  1871. // i, r->nickname);
  1872. if (! node->is_running)
  1873. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1874. continue;
  1875. if (! node->is_valid)
  1876. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1877. continue;
  1878. if (! node_has_descriptor(node))
  1879. continue;
  1880. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1881. * allows this node in some places, then we're getting an inaccurate
  1882. * count. For now, be conservative and don't count it. But later we
  1883. * should try to be smarter. */
  1884. ++num;
  1885. } SMARTLIST_FOREACH_END(node);
  1886. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1887. return num;
  1888. }
  1889. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1890. * This function is used to extend cpath by another hop.
  1891. */
  1892. void
  1893. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1894. {
  1895. if (*head_ptr) {
  1896. new_hop->next = (*head_ptr);
  1897. new_hop->prev = (*head_ptr)->prev;
  1898. (*head_ptr)->prev->next = new_hop;
  1899. (*head_ptr)->prev = new_hop;
  1900. } else {
  1901. *head_ptr = new_hop;
  1902. new_hop->prev = new_hop->next = new_hop;
  1903. }
  1904. }
  1905. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1906. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1907. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1908. * circuit. In particular, make sure we don't pick the exit node or its
  1909. * family, and make sure we don't duplicate any previous nodes or their
  1910. * families. */
  1911. static const node_t *
  1912. choose_good_middle_server(uint8_t purpose,
  1913. cpath_build_state_t *state,
  1914. crypt_path_t *head,
  1915. int cur_len)
  1916. {
  1917. int i;
  1918. const node_t *r, *choice;
  1919. crypt_path_t *cpath;
  1920. smartlist_t *excluded;
  1921. const or_options_t *options = get_options();
  1922. router_crn_flags_t flags = CRN_NEED_DESC;
  1923. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1924. purpose <= CIRCUIT_PURPOSE_MAX_);
  1925. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1926. excluded = smartlist_new();
  1927. if ((r = build_state_get_exit_node(state))) {
  1928. nodelist_add_node_and_family(excluded, r);
  1929. }
  1930. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1931. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1932. nodelist_add_node_and_family(excluded, r);
  1933. }
  1934. }
  1935. if (state->need_uptime)
  1936. flags |= CRN_NEED_UPTIME;
  1937. if (state->need_capacity)
  1938. flags |= CRN_NEED_CAPACITY;
  1939. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1940. flags |= CRN_ALLOW_INVALID;
  1941. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1942. smartlist_free(excluded);
  1943. return choice;
  1944. }
  1945. /** Pick a good entry server for the circuit to be built according to
  1946. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1947. * router (if we're an OR), and respect firewall settings; if we're
  1948. * configured to use entry guards, return one.
  1949. *
  1950. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1951. * guard, not for any particular circuit.
  1952. */
  1953. static const node_t *
  1954. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1955. {
  1956. const node_t *choice;
  1957. smartlist_t *excluded;
  1958. const or_options_t *options = get_options();
  1959. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1960. const node_t *node;
  1961. if (state && options->UseEntryGuards &&
  1962. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1963. /* This request is for an entry server to use for a regular circuit,
  1964. * and we use entry guard nodes. Just return one of the guard nodes. */
  1965. return choose_random_entry(state);
  1966. }
  1967. excluded = smartlist_new();
  1968. if (state && (node = build_state_get_exit_node(state))) {
  1969. /* Exclude the exit node from the state, if we have one. Also exclude its
  1970. * family. */
  1971. nodelist_add_node_and_family(excluded, node);
  1972. }
  1973. if (firewall_is_fascist_or()) {
  1974. /* Exclude all ORs that we can't reach through our firewall */
  1975. smartlist_t *nodes = nodelist_get_list();
  1976. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1977. if (!fascist_firewall_allows_node(node))
  1978. smartlist_add(excluded, (void*)node);
  1979. });
  1980. }
  1981. /* and exclude current entry guards and their families, if applicable */
  1982. if (options->UseEntryGuards) {
  1983. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1984. {
  1985. if ((node = node_get_by_id(entry->identity))) {
  1986. nodelist_add_node_and_family(excluded, node);
  1987. }
  1988. });
  1989. }
  1990. if (state) {
  1991. if (state->need_uptime)
  1992. flags |= CRN_NEED_UPTIME;
  1993. if (state->need_capacity)
  1994. flags |= CRN_NEED_CAPACITY;
  1995. }
  1996. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1997. flags |= CRN_ALLOW_INVALID;
  1998. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1999. smartlist_free(excluded);
  2000. return choice;
  2001. }
  2002. /** Return the first non-open hop in cpath, or return NULL if all
  2003. * hops are open. */
  2004. static crypt_path_t *
  2005. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2006. {
  2007. crypt_path_t *hop = cpath;
  2008. do {
  2009. if (hop->state != CPATH_STATE_OPEN)
  2010. return hop;
  2011. hop = hop->next;
  2012. } while (hop != cpath);
  2013. return NULL;
  2014. }
  2015. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2016. * based on <b>state</b>. Append the hop info to head_ptr.
  2017. */
  2018. static int
  2019. onion_extend_cpath(origin_circuit_t *circ)
  2020. {
  2021. uint8_t purpose = circ->base_.purpose;
  2022. cpath_build_state_t *state = circ->build_state;
  2023. int cur_len = circuit_get_cpath_len(circ);
  2024. extend_info_t *info = NULL;
  2025. if (cur_len >= state->desired_path_len) {
  2026. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2027. state->desired_path_len);
  2028. return 1;
  2029. }
  2030. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2031. state->desired_path_len);
  2032. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2033. info = extend_info_dup(state->chosen_exit);
  2034. } else if (cur_len == 0) { /* picking first node */
  2035. const node_t *r = choose_good_entry_server(purpose, state);
  2036. if (r) {
  2037. /* If we're a client, use the preferred address rather than the
  2038. primary address, for potentially connecting to an IPv6 OR
  2039. port. */
  2040. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  2041. tor_assert(info);
  2042. }
  2043. } else {
  2044. const node_t *r =
  2045. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2046. if (r) {
  2047. info = extend_info_from_node(r, 0);
  2048. tor_assert(info);
  2049. }
  2050. }
  2051. if (!info) {
  2052. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2053. "this circuit.", cur_len);
  2054. return -1;
  2055. }
  2056. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2057. extend_info_describe(info),
  2058. cur_len+1, build_state_get_exit_nickname(state));
  2059. onion_append_hop(&circ->cpath, info);
  2060. extend_info_free(info);
  2061. return 0;
  2062. }
  2063. /** Create a new hop, annotate it with information about its
  2064. * corresponding router <b>choice</b>, and append it to the
  2065. * end of the cpath <b>head_ptr</b>. */
  2066. static int
  2067. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2068. {
  2069. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2070. /* link hop into the cpath, at the end. */
  2071. onion_append_to_cpath(head_ptr, hop);
  2072. hop->magic = CRYPT_PATH_MAGIC;
  2073. hop->state = CPATH_STATE_CLOSED;
  2074. hop->extend_info = extend_info_dup(choice);
  2075. hop->package_window = circuit_initial_package_window();
  2076. hop->deliver_window = CIRCWINDOW_START;
  2077. return 0;
  2078. }
  2079. /** Allocate a new extend_info object based on the various arguments. */
  2080. extend_info_t *
  2081. extend_info_new(const char *nickname, const char *digest,
  2082. crypto_pk_t *onion_key,
  2083. const tor_addr_t *addr, uint16_t port)
  2084. {
  2085. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2086. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2087. if (nickname)
  2088. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2089. if (onion_key)
  2090. info->onion_key = crypto_pk_dup_key(onion_key);
  2091. tor_addr_copy(&info->addr, addr);
  2092. info->port = port;
  2093. return info;
  2094. }
  2095. /** Allocate and return a new extend_info that can be used to build a
  2096. * circuit to or through the node <b>node</b>. Use the primary address
  2097. * of the node (i.e. its IPv4 address) unless
  2098. * <b>for_direct_connect</b> is true, in which case the preferred
  2099. * address is used instead. May return NULL if there is not enough
  2100. * info about <b>node</b> to extend to it--for example, if there is no
  2101. * routerinfo_t or microdesc_t.
  2102. **/
  2103. extend_info_t *
  2104. extend_info_from_node(const node_t *node, int for_direct_connect)
  2105. {
  2106. tor_addr_port_t ap;
  2107. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2108. return NULL;
  2109. if (for_direct_connect)
  2110. node_get_pref_orport(node, &ap);
  2111. else
  2112. node_get_prim_orport(node, &ap);
  2113. log_debug(LD_CIRC, "using %s for %s",
  2114. fmt_addrport(&ap.addr, ap.port),
  2115. node->ri ? node->ri->nickname : node->rs->nickname);
  2116. if (node->ri)
  2117. return extend_info_new(node->ri->nickname,
  2118. node->identity,
  2119. node->ri->onion_pkey,
  2120. &ap.addr,
  2121. ap.port);
  2122. else if (node->rs && node->md)
  2123. return extend_info_new(node->rs->nickname,
  2124. node->identity,
  2125. node->md->onion_pkey,
  2126. &ap.addr,
  2127. ap.port);
  2128. else
  2129. return NULL;
  2130. }
  2131. /** Release storage held by an extend_info_t struct. */
  2132. void
  2133. extend_info_free(extend_info_t *info)
  2134. {
  2135. if (!info)
  2136. return;
  2137. crypto_pk_free(info->onion_key);
  2138. tor_free(info);
  2139. }
  2140. /** Allocate and return a new extend_info_t with the same contents as
  2141. * <b>info</b>. */
  2142. extend_info_t *
  2143. extend_info_dup(extend_info_t *info)
  2144. {
  2145. extend_info_t *newinfo;
  2146. tor_assert(info);
  2147. newinfo = tor_malloc(sizeof(extend_info_t));
  2148. memcpy(newinfo, info, sizeof(extend_info_t));
  2149. if (info->onion_key)
  2150. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2151. else
  2152. newinfo->onion_key = NULL;
  2153. return newinfo;
  2154. }
  2155. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2156. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2157. * the chosen exit, return NULL.
  2158. */
  2159. const node_t *
  2160. build_state_get_exit_node(cpath_build_state_t *state)
  2161. {
  2162. if (!state || !state->chosen_exit)
  2163. return NULL;
  2164. return node_get_by_id(state->chosen_exit->identity_digest);
  2165. }
  2166. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2167. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2168. * chosen exit, return NULL.
  2169. */
  2170. const char *
  2171. build_state_get_exit_nickname(cpath_build_state_t *state)
  2172. {
  2173. if (!state || !state->chosen_exit)
  2174. return NULL;
  2175. return state->chosen_exit->nickname;
  2176. }