circuitbuild.c 81 KB

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