circuitbuild.c 81 KB

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