circuituse.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  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-2009, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuituse.c
  8. * \brief Launch the right sort of circuits and attach streams to them.
  9. **/
  10. #include "or.h"
  11. /********* START VARIABLES **********/
  12. extern circuit_t *global_circuitlist; /* from circuitlist.c */
  13. /********* END VARIABLES ************/
  14. static void circuit_expire_old_circuits(time_t now);
  15. static void circuit_increment_failure_count(void);
  16. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  17. * Else return 0.
  18. */
  19. static int
  20. circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
  21. int must_be_open, uint8_t purpose,
  22. int need_uptime, int need_internal,
  23. time_t now)
  24. {
  25. routerinfo_t *exitrouter;
  26. cpath_build_state_t *build_state;
  27. tor_assert(circ);
  28. tor_assert(conn);
  29. tor_assert(conn->socks_request);
  30. if (!CIRCUIT_IS_ORIGIN(circ))
  31. return 0; /* this circ doesn't start at us */
  32. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  33. return 0; /* ignore non-open circs */
  34. if (circ->marked_for_close)
  35. return 0;
  36. /* if this circ isn't our purpose, skip. */
  37. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  38. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  39. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  40. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  41. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  42. return 0;
  43. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  44. !must_be_open) {
  45. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  46. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  47. return 0;
  48. } else {
  49. if (purpose != circ->purpose)
  50. return 0;
  51. }
  52. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  53. if (circ->timestamp_dirty &&
  54. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  55. return 0;
  56. /* decide if this circ is suitable for this conn */
  57. /* for rend circs, circ->cpath->prev is not the last router in the
  58. * circuit, it's the magical extra bob hop. so just check the nickname
  59. * of the one we meant to finish at.
  60. */
  61. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  62. exitrouter = build_state_get_exit_router(build_state);
  63. if (need_uptime && !build_state->need_uptime)
  64. return 0;
  65. if (need_internal != build_state->is_internal)
  66. return 0;
  67. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  68. if (!exitrouter && !build_state->onehop_tunnel) {
  69. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  70. return 0; /* this circuit is screwed and doesn't know it yet,
  71. * or is a rendezvous circuit. */
  72. }
  73. if (build_state->onehop_tunnel) {
  74. if (!conn->want_onehop) {
  75. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  76. return 0;
  77. }
  78. tor_assert(conn->chosen_exit_name);
  79. if (build_state->chosen_exit) {
  80. char digest[DIGEST_LEN];
  81. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  82. return 0; /* broken digest, we don't want it */
  83. if (memcmp(digest, build_state->chosen_exit->identity_digest,
  84. DIGEST_LEN))
  85. return 0; /* this is a circuit to somewhere else */
  86. if (tor_digest_is_zero(digest)) {
  87. /* we don't know the digest; have to compare addr:port */
  88. tor_addr_t addr;
  89. int r = tor_addr_from_str(&addr, conn->socks_request->address);
  90. if (r < 0 ||
  91. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  92. build_state->chosen_exit->port != conn->socks_request->port)
  93. return 0;
  94. }
  95. }
  96. } else {
  97. if (conn->want_onehop) {
  98. /* don't use three-hop circuits -- that could hurt our anonymity. */
  99. return 0;
  100. }
  101. }
  102. if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter)) {
  103. /* can't exit from this router */
  104. return 0;
  105. }
  106. } else { /* not general */
  107. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  108. if ((conn->rend_data && !ocirc->rend_data) ||
  109. (!conn->rend_data && ocirc->rend_data) ||
  110. (conn->rend_data && ocirc->rend_data &&
  111. rend_cmp_service_ids(conn->rend_data->onion_address,
  112. ocirc->rend_data->onion_address))) {
  113. /* this circ is not for this conn */
  114. return 0;
  115. }
  116. }
  117. return 1;
  118. }
  119. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  120. * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
  121. */
  122. static int
  123. circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
  124. {
  125. switch (purpose) {
  126. case CIRCUIT_PURPOSE_C_GENERAL:
  127. /* if it's used but less dirty it's best;
  128. * else if it's more recently created it's best
  129. */
  130. if (b->timestamp_dirty) {
  131. if (a->timestamp_dirty &&
  132. a->timestamp_dirty > b->timestamp_dirty)
  133. return 1;
  134. } else {
  135. if (a->timestamp_dirty ||
  136. a->timestamp_created > b->timestamp_created)
  137. return 1;
  138. if (CIRCUIT_IS_ORIGIN(b) &&
  139. TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
  140. return 1;
  141. }
  142. break;
  143. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  144. /* the closer it is to ack_wait the better it is */
  145. if (a->purpose > b->purpose)
  146. return 1;
  147. break;
  148. case CIRCUIT_PURPOSE_C_REND_JOINED:
  149. /* the closer it is to rend_joined the better it is */
  150. if (a->purpose > b->purpose)
  151. return 1;
  152. break;
  153. }
  154. return 0;
  155. }
  156. /** Find the best circ that conn can use, preferably one which is
  157. * dirty. Circ must not be too old.
  158. *
  159. * Conn must be defined.
  160. *
  161. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  162. *
  163. * circ_purpose specifies what sort of circuit we must have.
  164. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  165. *
  166. * If it's REND_JOINED and must_be_open==0, then return the closest
  167. * rendezvous-purposed circuit that you can find.
  168. *
  169. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  170. * closest introduce-purposed circuit that you can find.
  171. */
  172. static origin_circuit_t *
  173. circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
  174. int need_uptime, int need_internal)
  175. {
  176. circuit_t *circ, *best=NULL;
  177. time_t now = time(NULL);
  178. int intro_going_on_but_too_old = 0;
  179. tor_assert(conn);
  180. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  181. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  182. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  183. for (circ=global_circuitlist;circ;circ = circ->next) {
  184. if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
  185. need_uptime,need_internal,now))
  186. continue;
  187. /* XXX022 make this 15 be a function of circuit finishing times we've
  188. * seen lately, a la Fallon Chen's GSoC work -RD */
  189. #define REND_PARALLEL_INTRO_DELAY 15
  190. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  191. !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
  192. circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
  193. intro_going_on_but_too_old = 1;
  194. continue;
  195. }
  196. /* now this is an acceptable circ to hand back. but that doesn't
  197. * mean it's the *best* circ to hand back. try to decide.
  198. */
  199. if (!best || circuit_is_better(circ,best,purpose))
  200. best = circ;
  201. }
  202. if (!best && intro_going_on_but_too_old)
  203. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  204. "right now, but it has already taken quite a while. Starting "
  205. "one in parallel.");
  206. return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
  207. }
  208. /** Check whether, according to the policies in <b>options</b>, the
  209. * circuit <b>circ</b> makes sense. */
  210. /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
  211. int
  212. circuit_conforms_to_options(const origin_circuit_t *circ,
  213. const or_options_t *options)
  214. {
  215. const crypt_path_t *cpath, *cpath_next = NULL;
  216. for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
  217. cpath = cpath_next) {
  218. cpath_next = cpath->next;
  219. if (routerset_contains_extendinfo(options->ExcludeNodes,
  220. cpath->extend_info))
  221. return 0;
  222. if (cpath->next == circ->cpath) {
  223. /* This is apparently the exit node. */
  224. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  225. cpath->extend_info))
  226. return 0;
  227. }
  228. }
  229. return 1;
  230. }
  231. /** Close all circuits that start at us, aren't open, and were born
  232. * at least CircuitBuildTimeout seconds ago.
  233. */
  234. void
  235. circuit_expire_building(time_t now)
  236. {
  237. circuit_t *victim, *circ = global_circuitlist;
  238. time_t general_cutoff = now - get_options()->CircuitBuildTimeout;
  239. time_t begindir_cutoff = now - get_options()->CircuitBuildTimeout/2;
  240. time_t introcirc_cutoff = begindir_cutoff;
  241. cpath_build_state_t *build_state;
  242. while (circ) {
  243. time_t cutoff;
  244. victim = circ;
  245. circ = circ->next;
  246. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  247. victim->marked_for_close) /* don't mess with marked circs */
  248. continue;
  249. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  250. if (build_state && build_state->onehop_tunnel)
  251. cutoff = begindir_cutoff;
  252. else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  253. cutoff = introcirc_cutoff;
  254. else
  255. cutoff = general_cutoff;
  256. if (victim->timestamp_created > cutoff)
  257. continue; /* it's still young, leave it alone */
  258. #if 0
  259. /* some debug logs, to help track bugs */
  260. if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  261. victim->timestamp_created <= introcirc_cutoff &&
  262. victim->timestamp_created > general_cutoff)
  263. log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
  264. "would not have done if it had been a general circuit.");
  265. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  266. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  267. if (!victim->timestamp_dirty)
  268. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d)."
  269. "(clean).",
  270. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  271. victim->purpose, victim->build_state->chosen_exit_name,
  272. victim->n_circ_id);
  273. else
  274. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). "
  275. "%d secs since dirty.",
  276. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  277. victim->purpose, victim->build_state->chosen_exit_name,
  278. victim->n_circ_id,
  279. (int)(now - victim->timestamp_dirty));
  280. }
  281. #endif
  282. /* if circ is !open, or if it's open but purpose is a non-finished
  283. * intro or rend, then mark it for close */
  284. if (victim->state == CIRCUIT_STATE_OPEN) {
  285. switch (victim->purpose) {
  286. default: /* most open circuits can be left alone. */
  287. continue; /* yes, continue inside a switch refers to the nearest
  288. * enclosing loop. C is smart. */
  289. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  290. case CIRCUIT_PURPOSE_C_INTRODUCING:
  291. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  292. break; /* too old, need to die */
  293. case CIRCUIT_PURPOSE_C_REND_READY:
  294. /* it's a rend_ready circ -- has it already picked a query? */
  295. /* c_rend_ready circs measure age since timestamp_dirty,
  296. * because that's set when they switch purposes
  297. */
  298. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  299. victim->timestamp_dirty > cutoff)
  300. continue;
  301. break;
  302. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  303. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  304. /* rend and intro circs become dirty each time they
  305. * make an introduction attempt. so timestamp_dirty
  306. * will reflect the time since the last attempt.
  307. */
  308. if (victim->timestamp_dirty > cutoff)
  309. continue;
  310. break;
  311. }
  312. }
  313. if (victim->n_conn)
  314. log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  315. victim->n_conn->_base.address, victim->n_conn->_base.port,
  316. victim->n_circ_id,
  317. victim->state, circuit_state_to_string(victim->state),
  318. victim->purpose);
  319. else
  320. log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  321. victim->n_circ_id, victim->state,
  322. circuit_state_to_string(victim->state), victim->purpose);
  323. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  324. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  325. }
  326. }
  327. /** Remove any elements in <b>needed_ports</b> that are handled by an
  328. * open or in-progress circuit.
  329. */
  330. void
  331. circuit_remove_handled_ports(smartlist_t *needed_ports)
  332. {
  333. int i;
  334. uint16_t *port;
  335. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  336. port = smartlist_get(needed_ports, i);
  337. tor_assert(*port);
  338. if (circuit_stream_is_being_handled(NULL, *port,
  339. MIN_CIRCUITS_HANDLING_STREAM)) {
  340. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  341. smartlist_del(needed_ports, i--);
  342. tor_free(port);
  343. } else {
  344. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  345. }
  346. }
  347. }
  348. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  349. * will have an acceptable exit node for exit stream <b>conn</b> if it
  350. * is defined, else for "*:port".
  351. * Else return 0.
  352. */
  353. int
  354. circuit_stream_is_being_handled(edge_connection_t *conn,
  355. uint16_t port, int min)
  356. {
  357. circuit_t *circ;
  358. routerinfo_t *exitrouter;
  359. int num=0;
  360. time_t now = time(NULL);
  361. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  362. conn ? conn->socks_request->port : port);
  363. for (circ=global_circuitlist;circ;circ = circ->next) {
  364. if (CIRCUIT_IS_ORIGIN(circ) &&
  365. !circ->marked_for_close &&
  366. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  367. (!circ->timestamp_dirty ||
  368. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  369. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  370. if (build_state->is_internal || build_state->onehop_tunnel)
  371. continue;
  372. exitrouter = build_state_get_exit_router(build_state);
  373. if (exitrouter && (!need_uptime || build_state->need_uptime)) {
  374. int ok;
  375. if (conn) {
  376. ok = connection_ap_can_use_exit(conn, exitrouter);
  377. } else {
  378. addr_policy_result_t r = compare_addr_to_addr_policy(
  379. 0, port, exitrouter->exit_policy);
  380. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  381. }
  382. if (ok) {
  383. if (++num >= min)
  384. return 1;
  385. }
  386. }
  387. }
  388. }
  389. return 0;
  390. }
  391. /** Don't keep more than this many unused open circuits around. */
  392. #define MAX_UNUSED_OPEN_CIRCUITS 12
  393. /** Figure out how many circuits we have open that are clean. Make
  394. * sure it's enough for all the upcoming behaviors we predict we'll have.
  395. * But if we have too many, close the not-so-useful ones.
  396. */
  397. static void
  398. circuit_predict_and_launch_new(void)
  399. {
  400. circuit_t *circ;
  401. int num=0, num_internal=0, num_uptime_internal=0;
  402. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  403. int port_needs_uptime=0, port_needs_capacity=1;
  404. time_t now = time(NULL);
  405. int flags = 0;
  406. /* First, count how many of each type of circuit we have already. */
  407. for (circ=global_circuitlist;circ;circ = circ->next) {
  408. cpath_build_state_t *build_state;
  409. if (!CIRCUIT_IS_ORIGIN(circ))
  410. continue;
  411. if (circ->marked_for_close)
  412. continue; /* don't mess with marked circs */
  413. if (circ->timestamp_dirty)
  414. continue; /* only count clean circs */
  415. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  416. continue; /* only pay attention to general-purpose circs */
  417. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  418. if (build_state->onehop_tunnel)
  419. continue;
  420. num++;
  421. if (build_state->is_internal)
  422. num_internal++;
  423. if (build_state->need_uptime && build_state->is_internal)
  424. num_uptime_internal++;
  425. }
  426. /* If that's enough, then stop now. */
  427. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  428. return; /* we already have many, making more probably will hurt */
  429. /* Second, see if we need any more exit circuits. */
  430. /* check if we know of a port that's been requested recently
  431. * and no circuit is currently available that can handle it. */
  432. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  433. &port_needs_capacity)) {
  434. if (port_needs_uptime)
  435. flags |= CIRCLAUNCH_NEED_UPTIME;
  436. if (port_needs_capacity)
  437. flags |= CIRCLAUNCH_NEED_CAPACITY;
  438. log_info(LD_CIRC,
  439. "Have %d clean circs (%d internal), need another exit circ.",
  440. num, num_internal);
  441. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  442. return;
  443. }
  444. /* Third, see if we need any more hidden service (server) circuits. */
  445. if (num_rend_services() && num_uptime_internal < 3) {
  446. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  447. CIRCLAUNCH_IS_INTERNAL);
  448. log_info(LD_CIRC,
  449. "Have %d clean circs (%d internal), need another internal "
  450. "circ for my hidden service.",
  451. num, num_internal);
  452. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  453. return;
  454. }
  455. /* Fourth, see if we need any more hidden service (client) circuits. */
  456. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  457. &hidserv_needs_capacity) &&
  458. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  459. num_internal<2)) {
  460. if (hidserv_needs_uptime)
  461. flags |= CIRCLAUNCH_NEED_UPTIME;
  462. if (hidserv_needs_capacity)
  463. flags |= CIRCLAUNCH_NEED_CAPACITY;
  464. flags |= CIRCLAUNCH_IS_INTERNAL;
  465. log_info(LD_CIRC,
  466. "Have %d clean circs (%d uptime-internal, %d internal), need"
  467. " another hidserv circ.",
  468. num, num_uptime_internal, num_internal);
  469. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  470. return;
  471. }
  472. }
  473. /** Build a new test circuit every 5 minutes */
  474. #define TESTING_CIRCUIT_INTERVAL 300
  475. /** This function is called once a second, if router_have_min_dir_info() is
  476. * true. Its job is to make sure all services we offer have enough circuits
  477. * available. Some services just want enough circuits for current tasks,
  478. * whereas others want a minimum set of idle circuits hanging around.
  479. */
  480. void
  481. circuit_build_needed_circs(time_t now)
  482. {
  483. static time_t time_to_new_circuit = 0;
  484. or_options_t *options = get_options();
  485. /* launch a new circ for any pending streams that need one */
  486. connection_ap_attach_pending();
  487. /* make sure any hidden services have enough intro points */
  488. rend_services_introduce();
  489. if (time_to_new_circuit < now) {
  490. circuit_reset_failure_count(1);
  491. time_to_new_circuit = now + options->NewCircuitPeriod;
  492. if (proxy_mode(get_options()))
  493. addressmap_clean(now);
  494. circuit_expire_old_circuits(now);
  495. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  496. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  497. if (get_options()->RunTesting &&
  498. circ &&
  499. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  500. log_fn(LOG_INFO,"Creating a new testing circuit.");
  501. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
  502. }
  503. #endif
  504. }
  505. if (!options->DisablePredictedCircuits)
  506. circuit_predict_and_launch_new();
  507. }
  508. /** If the stream <b>conn</b> is a member of any of the linked
  509. * lists of <b>circ</b>, then remove it from the list.
  510. */
  511. void
  512. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  513. {
  514. edge_connection_t *prevconn;
  515. tor_assert(circ);
  516. tor_assert(conn);
  517. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  518. conn->on_circuit = NULL;
  519. if (CIRCUIT_IS_ORIGIN(circ)) {
  520. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  521. if (conn == origin_circ->p_streams) {
  522. origin_circ->p_streams = conn->next_stream;
  523. return;
  524. }
  525. for (prevconn = origin_circ->p_streams;
  526. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  527. prevconn = prevconn->next_stream)
  528. ;
  529. if (prevconn && prevconn->next_stream) {
  530. prevconn->next_stream = conn->next_stream;
  531. return;
  532. }
  533. } else {
  534. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  535. if (conn == or_circ->n_streams) {
  536. or_circ->n_streams = conn->next_stream;
  537. return;
  538. }
  539. if (conn == or_circ->resolving_streams) {
  540. or_circ->resolving_streams = conn->next_stream;
  541. return;
  542. }
  543. for (prevconn = or_circ->n_streams;
  544. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  545. prevconn = prevconn->next_stream)
  546. ;
  547. if (prevconn && prevconn->next_stream) {
  548. prevconn->next_stream = conn->next_stream;
  549. return;
  550. }
  551. for (prevconn = or_circ->resolving_streams;
  552. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  553. prevconn = prevconn->next_stream)
  554. ;
  555. if (prevconn && prevconn->next_stream) {
  556. prevconn->next_stream = conn->next_stream;
  557. return;
  558. }
  559. }
  560. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  561. /* Don't give an error here; it's harmless. */
  562. tor_fragile_assert();
  563. }
  564. /** Find each circuit that has been unused for too long, or dirty
  565. * for too long and has no streams on it: mark it for close.
  566. */
  567. static void
  568. circuit_expire_old_circuits(time_t now)
  569. {
  570. circuit_t *circ;
  571. time_t cutoff = now - get_options()->CircuitIdleTimeout;
  572. for (circ = global_circuitlist; circ; circ = circ->next) {
  573. if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
  574. continue;
  575. /* If the circuit has been dirty for too long, and there are no streams
  576. * on it, mark it for close.
  577. */
  578. if (circ->timestamp_dirty &&
  579. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
  580. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  581. log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
  582. circ->n_circ_id, (int)(now - circ->timestamp_dirty),
  583. circ->purpose);
  584. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  585. } else if (!circ->timestamp_dirty &&
  586. circ->state == CIRCUIT_STATE_OPEN &&
  587. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  588. if (circ->timestamp_created < cutoff) {
  589. log_debug(LD_CIRC,
  590. "Closing circuit that has been unused for %d seconds.",
  591. (int)(now - circ->timestamp_created));
  592. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  593. }
  594. }
  595. }
  596. }
  597. /** Number of testing circuits we want open before testing our bandwidth. */
  598. #define NUM_PARALLEL_TESTING_CIRCS 4
  599. /** True iff we've ever had enough testing circuits open to test our
  600. * bandwidth. */
  601. static int have_performed_bandwidth_test = 0;
  602. /** Reset have_performed_bandwidth_test, so we'll start building
  603. * testing circuits again so we can exercise our bandwidth. */
  604. void
  605. reset_bandwidth_test(void)
  606. {
  607. have_performed_bandwidth_test = 0;
  608. }
  609. /** Return 1 if we've already exercised our bandwidth, or if we
  610. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  611. * established or on the way. Else return 0.
  612. */
  613. int
  614. circuit_enough_testing_circs(void)
  615. {
  616. circuit_t *circ;
  617. int num = 0;
  618. if (have_performed_bandwidth_test)
  619. return 1;
  620. for (circ = global_circuitlist; circ; circ = circ->next) {
  621. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  622. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  623. circ->state == CIRCUIT_STATE_OPEN)
  624. num++;
  625. }
  626. return num >= NUM_PARALLEL_TESTING_CIRCS;
  627. }
  628. /** A testing circuit has completed. Take whatever stats we want.
  629. * Noticing reachability is taken care of in onionskin_answer(),
  630. * so there's no need to record anything here. But if we still want
  631. * to do the bandwidth test, and we now have enough testing circuits
  632. * open, do it.
  633. */
  634. static void
  635. circuit_testing_opened(origin_circuit_t *circ)
  636. {
  637. if (have_performed_bandwidth_test ||
  638. !check_whether_orport_reachable()) {
  639. /* either we've already done everything we want with testing circuits,
  640. * or this testing circuit became open due to a fluke, e.g. we picked
  641. * a last hop where we already had the connection open due to an
  642. * outgoing local circuit. */
  643. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  644. } else if (circuit_enough_testing_circs()) {
  645. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  646. have_performed_bandwidth_test = 1;
  647. } else
  648. consider_testing_reachability(1, 0);
  649. }
  650. /** A testing circuit has failed to build. Take whatever stats we want. */
  651. static void
  652. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  653. {
  654. routerinfo_t *me = router_get_my_routerinfo();
  655. if (server_mode(get_options()) && check_whether_orport_reachable())
  656. return;
  657. if (!me)
  658. return;
  659. log_info(LD_GENERAL,
  660. "Our testing circuit (to see if your ORPort is reachable) "
  661. "has failed. I'll try again later.");
  662. control_event_server_status(LOG_WARN, "REACHABILITY_FAILED ORADDRESS=%s:%d",
  663. me->address, me->or_port);
  664. /* These aren't used yet. */
  665. (void)circ;
  666. (void)at_last_hop;
  667. }
  668. /** The circuit <b>circ</b> has just become open. Take the next
  669. * step: for rendezvous circuits, we pass circ to the appropriate
  670. * function in rendclient or rendservice. For general circuits, we
  671. * call connection_ap_attach_pending, which looks for pending streams
  672. * that could use circ.
  673. */
  674. void
  675. circuit_has_opened(origin_circuit_t *circ)
  676. {
  677. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  678. switch (TO_CIRCUIT(circ)->purpose) {
  679. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  680. rend_client_rendcirc_has_opened(circ);
  681. connection_ap_attach_pending();
  682. break;
  683. case CIRCUIT_PURPOSE_C_INTRODUCING:
  684. rend_client_introcirc_has_opened(circ);
  685. break;
  686. case CIRCUIT_PURPOSE_C_GENERAL:
  687. /* Tell any AP connections that have been waiting for a new
  688. * circuit that one is ready. */
  689. connection_ap_attach_pending();
  690. break;
  691. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  692. /* at Bob, waiting for introductions */
  693. rend_service_intro_has_opened(circ);
  694. break;
  695. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  696. /* at Bob, connecting to rend point */
  697. rend_service_rendezvous_has_opened(circ);
  698. break;
  699. case CIRCUIT_PURPOSE_TESTING:
  700. circuit_testing_opened(circ);
  701. break;
  702. /* default:
  703. * This won't happen in normal operation, but might happen if the
  704. * controller did it. Just let it slide. */
  705. }
  706. }
  707. /** Called whenever a circuit could not be successfully built.
  708. */
  709. void
  710. circuit_build_failed(origin_circuit_t *circ)
  711. {
  712. /* we should examine circ and see if it failed because of
  713. * the last hop or an earlier hop. then use this info below.
  714. */
  715. int failed_at_last_hop = 0;
  716. /* If the last hop isn't open, and the second-to-last is, we failed
  717. * at the last hop. */
  718. if (circ->cpath &&
  719. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  720. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  721. failed_at_last_hop = 1;
  722. }
  723. if (circ->cpath &&
  724. circ->cpath->state != CPATH_STATE_OPEN) {
  725. /* We failed at the first hop. If there's an OR connection
  726. * to blame, blame it. Also, avoid this relay for a while, and
  727. * fail any one-hop directory fetches destined for it. */
  728. const char *n_conn_id = circ->cpath->extend_info->identity_digest;
  729. if (circ->_base.n_conn) {
  730. or_connection_t *n_conn = circ->_base.n_conn;
  731. log_info(LD_OR,
  732. "Our circuit failed to get a response from the first hop "
  733. "(%s:%d). I'm going to try to rotate to a better connection.",
  734. n_conn->_base.address, n_conn->_base.port);
  735. n_conn->is_bad_for_new_circs = 1;
  736. }
  737. if (n_conn_id) {
  738. entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
  739. /* if there are any one-hop streams waiting on this circuit, fail
  740. * them now so they can retry elsewhere. */
  741. connection_ap_fail_onehop(n_conn_id, circ->build_state);
  742. }
  743. }
  744. switch (circ->_base.purpose) {
  745. case CIRCUIT_PURPOSE_C_GENERAL:
  746. /* If we never built the circuit, note it as a failure. */
  747. circuit_increment_failure_count();
  748. if (failed_at_last_hop) {
  749. /* Make sure any streams that demand our last hop as their exit
  750. * know that it's unlikely to happen. */
  751. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  752. }
  753. break;
  754. case CIRCUIT_PURPOSE_TESTING:
  755. circuit_testing_failed(circ, failed_at_last_hop);
  756. break;
  757. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  758. /* at Bob, waiting for introductions */
  759. if (circ->_base.state != CIRCUIT_STATE_OPEN) {
  760. circuit_increment_failure_count();
  761. }
  762. /* no need to care here, because bob will rebuild intro
  763. * points periodically. */
  764. break;
  765. case CIRCUIT_PURPOSE_C_INTRODUCING:
  766. /* at Alice, connecting to intro point */
  767. /* Don't increment failure count, since Bob may have picked
  768. * the introduction point maliciously */
  769. /* Alice will pick a new intro point when this one dies, if
  770. * the stream in question still cares. No need to act here. */
  771. break;
  772. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  773. /* at Alice, waiting for Bob */
  774. circuit_increment_failure_count();
  775. /* Alice will pick a new rend point when this one dies, if
  776. * the stream in question still cares. No need to act here. */
  777. break;
  778. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  779. /* at Bob, connecting to rend point */
  780. /* Don't increment failure count, since Alice may have picked
  781. * the rendezvous point maliciously */
  782. log_info(LD_REND,
  783. "Couldn't connect to Alice's chosen rend point %s "
  784. "(%s hop failed).",
  785. escaped(build_state_get_exit_nickname(circ->build_state)),
  786. failed_at_last_hop?"last":"non-last");
  787. rend_service_relaunch_rendezvous(circ);
  788. break;
  789. /* default:
  790. * This won't happen in normal operation, but might happen if the
  791. * controller did it. Just let it slide. */
  792. }
  793. }
  794. /** Number of consecutive failures so far; should only be touched by
  795. * circuit_launch_new and circuit_*_failure_count.
  796. */
  797. static int n_circuit_failures = 0;
  798. /** Before the last time we called circuit_reset_failure_count(), were
  799. * there a lot of failures? */
  800. static int did_circs_fail_last_period = 0;
  801. /** Don't retry launching a new circuit if we try this many times with no
  802. * success. */
  803. #define MAX_CIRCUIT_FAILURES 5
  804. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  805. * details on arguments. */
  806. origin_circuit_t *
  807. circuit_launch_by_router(uint8_t purpose,
  808. routerinfo_t *exit, int flags)
  809. {
  810. origin_circuit_t *circ;
  811. extend_info_t *info = NULL;
  812. if (exit)
  813. info = extend_info_from_router(exit);
  814. circ = circuit_launch_by_extend_info(purpose, info, flags);
  815. if (info)
  816. extend_info_free(info);
  817. return circ;
  818. }
  819. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  820. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  821. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  822. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  823. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  824. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  825. * Return the newly allocated circuit on success, or NULL on failure. */
  826. origin_circuit_t *
  827. circuit_launch_by_extend_info(uint8_t purpose,
  828. extend_info_t *extend_info,
  829. int flags)
  830. {
  831. origin_circuit_t *circ;
  832. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  833. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  834. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  835. "circuit launch.");
  836. return NULL;
  837. }
  838. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  839. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  840. /* see if there are appropriate circs available to cannibalize. */
  841. /* XXX if we're planning to add a hop, perhaps we want to look for
  842. * internal circs rather than exit circs? -RD */
  843. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  844. if (circ) {
  845. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
  846. build_state_get_exit_nickname(circ->build_state), purpose);
  847. circ->_base.purpose = purpose;
  848. /* reset the birth date of this circ, else expire_building
  849. * will see it and think it's been trying to build since it
  850. * began. */
  851. circ->_base.timestamp_created = time(NULL);
  852. switch (purpose) {
  853. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  854. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  855. /* it's ready right now */
  856. break;
  857. case CIRCUIT_PURPOSE_C_INTRODUCING:
  858. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  859. case CIRCUIT_PURPOSE_C_GENERAL:
  860. /* need to add a new hop */
  861. tor_assert(extend_info);
  862. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  863. return NULL;
  864. break;
  865. default:
  866. log_warn(LD_BUG,
  867. "unexpected purpose %d when cannibalizing a circ.",
  868. purpose);
  869. tor_fragile_assert();
  870. return NULL;
  871. }
  872. return circ;
  873. }
  874. }
  875. if (did_circs_fail_last_period &&
  876. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  877. /* too many failed circs in a row. don't try. */
  878. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  879. return NULL;
  880. }
  881. /* try a circ. if it fails, circuit_mark_for_close will increment
  882. * n_circuit_failures */
  883. return circuit_establish_circuit(purpose, extend_info, flags);
  884. }
  885. /** Record another failure at opening a general circuit. When we have
  886. * too many, we'll stop trying for the remainder of this minute.
  887. */
  888. static void
  889. circuit_increment_failure_count(void)
  890. {
  891. ++n_circuit_failures;
  892. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  893. }
  894. /** Reset the failure count for opening general circuits. This means
  895. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  896. * stopping again.
  897. */
  898. void
  899. circuit_reset_failure_count(int timeout)
  900. {
  901. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  902. did_circs_fail_last_period = 1;
  903. else
  904. did_circs_fail_last_period = 0;
  905. n_circuit_failures = 0;
  906. }
  907. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  908. * there isn't one, and there isn't one on the way, launch one and return
  909. * 0. If it will never work, return -1.
  910. *
  911. * Write the found or in-progress or launched circ into *circp.
  912. */
  913. static int
  914. circuit_get_open_circ_or_launch(edge_connection_t *conn,
  915. uint8_t desired_circuit_purpose,
  916. origin_circuit_t **circp)
  917. {
  918. origin_circuit_t *circ;
  919. int check_exit_policy;
  920. int need_uptime, need_internal;
  921. int want_onehop;
  922. or_options_t *options = get_options();
  923. tor_assert(conn);
  924. tor_assert(circp);
  925. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  926. check_exit_policy =
  927. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  928. !conn->use_begindir &&
  929. !connection_edge_is_rendezvous_stream(conn);
  930. want_onehop = conn->want_onehop;
  931. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  932. smartlist_string_num_isin(options->LongLivedPorts,
  933. conn->socks_request->port);
  934. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  935. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  936. need_uptime, need_internal);
  937. if (circ) {
  938. *circp = circ;
  939. return 1; /* we're happy */
  940. }
  941. if (!want_onehop && !router_have_minimum_dir_info()) {
  942. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  943. int severity = LOG_NOTICE;
  944. /* FFFF if this is a tunnelled directory fetch, don't yell
  945. * as loudly. the user doesn't even know it's happening. */
  946. if (options->UseBridges && bridges_known_but_down()) {
  947. log_fn(severity, LD_APP|LD_DIR,
  948. "Application request when we're believed to be "
  949. "offline. Optimistically trying known bridges again.");
  950. bridges_retry_all();
  951. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  952. log_fn(severity, LD_APP|LD_DIR,
  953. "Application request when we're believed to be "
  954. "offline. Optimistically trying directory fetches again.");
  955. routerlist_retry_directory_downloads(time(NULL));
  956. }
  957. }
  958. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  959. * 1, or when all directory attempts fail and directory_all_unreachable()
  960. * kills it.
  961. */
  962. return 0;
  963. }
  964. /* Do we need to check exit policy? */
  965. if (check_exit_policy) {
  966. if (!conn->chosen_exit_name) {
  967. struct in_addr in;
  968. uint32_t addr = 0;
  969. if (tor_inet_aton(conn->socks_request->address, &in))
  970. addr = ntohl(in.s_addr);
  971. if (router_exit_policy_all_routers_reject(addr,
  972. conn->socks_request->port,
  973. need_uptime)) {
  974. log_notice(LD_APP,
  975. "No Tor server allows exit to %s:%d. Rejecting.",
  976. safe_str(conn->socks_request->address),
  977. conn->socks_request->port);
  978. return -1;
  979. }
  980. } else {
  981. /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
  982. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  983. int opt = conn->chosen_exit_optional;
  984. if (router && !connection_ap_can_use_exit(conn, router)) {
  985. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  986. "Requested exit point '%s' would refuse request. %s.",
  987. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  988. if (opt) {
  989. conn->chosen_exit_optional = 0;
  990. tor_free(conn->chosen_exit_name);
  991. /* Try again. */
  992. return circuit_get_open_circ_or_launch(conn,
  993. desired_circuit_purpose,
  994. circp);
  995. }
  996. return -1;
  997. }
  998. }
  999. }
  1000. /* is one already on the way? */
  1001. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1002. need_uptime, need_internal);
  1003. if (circ)
  1004. log_debug(LD_CIRC, "one on the way!");
  1005. if (!circ) {
  1006. extend_info_t *extend_info=NULL;
  1007. uint8_t new_circ_purpose;
  1008. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1009. /* need to pick an intro point */
  1010. tor_assert(conn->rend_data);
  1011. extend_info = rend_client_get_random_intro(conn->rend_data);
  1012. if (!extend_info) {
  1013. log_info(LD_REND,
  1014. "No intro points for '%s': refetching service descriptor.",
  1015. safe_str(conn->rend_data->onion_address));
  1016. /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
  1017. * arrives first. Exception: When using client authorization, only
  1018. * fetch v2 descriptors.*/
  1019. rend_client_refetch_v2_renddesc(conn->rend_data);
  1020. if (conn->rend_data->auth_type == REND_NO_AUTH)
  1021. rend_client_refetch_renddesc(conn->rend_data->onion_address);
  1022. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1023. return 0;
  1024. }
  1025. log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
  1026. extend_info->nickname,
  1027. safe_str(conn->rend_data->onion_address));
  1028. }
  1029. /* If we have specified a particular exit node for our
  1030. * connection, then be sure to open a circuit to that exit node.
  1031. */
  1032. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1033. if (conn->chosen_exit_name) {
  1034. routerinfo_t *r;
  1035. int opt = conn->chosen_exit_optional;
  1036. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1037. if (r) {
  1038. extend_info = extend_info_from_router(r);
  1039. } else {
  1040. log_debug(LD_DIR, "considering %d, %s",
  1041. want_onehop, conn->chosen_exit_name);
  1042. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1043. /* We're asking for a one-hop circuit to a router that
  1044. * we don't have a routerinfo about. Make up an extend_info. */
  1045. char digest[DIGEST_LEN];
  1046. char *hexdigest = conn->chosen_exit_name+1;
  1047. tor_addr_t addr;
  1048. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1049. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1050. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1051. return -1;
  1052. }
  1053. if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
  1054. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1055. escaped_safe_str(conn->socks_request->address));
  1056. return -1;
  1057. }
  1058. extend_info = extend_info_alloc(conn->chosen_exit_name+1,
  1059. digest, NULL, &addr,
  1060. conn->socks_request->port);
  1061. } else {
  1062. /* We will need an onion key for the router, and we
  1063. * don't have one. Refuse or relax requirements. */
  1064. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1065. "Requested exit point '%s' is not known. %s.",
  1066. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1067. if (opt) {
  1068. conn->chosen_exit_optional = 0;
  1069. tor_free(conn->chosen_exit_name);
  1070. /* Try again with no requested exit */
  1071. return circuit_get_open_circ_or_launch(conn,
  1072. desired_circuit_purpose,
  1073. circp);
  1074. }
  1075. return -1;
  1076. }
  1077. }
  1078. }
  1079. }
  1080. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1081. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1082. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1083. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1084. else
  1085. new_circ_purpose = desired_circuit_purpose;
  1086. {
  1087. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1088. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1089. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1090. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1091. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1092. flags);
  1093. }
  1094. if (extend_info)
  1095. extend_info_free(extend_info);
  1096. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  1097. /* help predict this next time */
  1098. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1099. if (circ) {
  1100. /* write the service_id into circ */
  1101. circ->rend_data = rend_data_dup(conn->rend_data);
  1102. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1103. circ->_base.state == CIRCUIT_STATE_OPEN)
  1104. rend_client_rendcirc_has_opened(circ);
  1105. }
  1106. }
  1107. }
  1108. if (!circ)
  1109. log_info(LD_APP,
  1110. "No safe circuit (purpose %d) ready for edge "
  1111. "connection; delaying.",
  1112. desired_circuit_purpose);
  1113. *circp = circ;
  1114. return 0;
  1115. }
  1116. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1117. * <b>circ</b>. */
  1118. static int
  1119. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1120. {
  1121. crypt_path_t *cpath, *cpath_next = NULL;
  1122. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1123. cpath_next = cpath->next;
  1124. if (crypt_path == cpath)
  1125. return 1;
  1126. }
  1127. return 0;
  1128. }
  1129. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1130. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1131. * hop in circ's cpath if <b>cpath</b> is NULL.
  1132. */
  1133. static void
  1134. link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
  1135. crypt_path_t *cpath)
  1136. {
  1137. /* add it into the linked list of streams on this circuit */
  1138. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1139. circ->_base.n_circ_id);
  1140. /* reset it, so we can measure circ timeouts */
  1141. apconn->_base.timestamp_lastread = time(NULL);
  1142. apconn->next_stream = circ->p_streams;
  1143. apconn->on_circuit = TO_CIRCUIT(circ);
  1144. /* assert_connection_ok(conn, time(NULL)); */
  1145. circ->p_streams = apconn;
  1146. if (cpath) { /* we were given one; use it */
  1147. tor_assert(cpath_is_on_circuit(circ, cpath));
  1148. apconn->cpath_layer = cpath;
  1149. } else { /* use the last hop in the circuit */
  1150. tor_assert(circ->cpath);
  1151. tor_assert(circ->cpath->prev);
  1152. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1153. apconn->cpath_layer = circ->cpath->prev;
  1154. }
  1155. }
  1156. /** If an exit wasn't specifically chosen, save the history for future
  1157. * use. */
  1158. static void
  1159. consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
  1160. {
  1161. int found_needle = 0;
  1162. or_options_t *options = get_options();
  1163. size_t len;
  1164. char *new_address;
  1165. char fp[HEX_DIGEST_LEN+1];
  1166. /* Search the addressmap for this conn's destination. */
  1167. /* If he's not in the address map.. */
  1168. if (!options->TrackHostExits ||
  1169. addressmap_have_mapping(conn->socks_request->address,
  1170. options->TrackHostExitsExpire))
  1171. return; /* nothing to track, or already mapped */
  1172. SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
  1173. if (cp[0] == '.') { /* match end */
  1174. if (cp[1] == '\0' ||
  1175. !strcasecmpend(conn->socks_request->address, cp) ||
  1176. !strcasecmp(conn->socks_request->address, &cp[1]))
  1177. found_needle = 1;
  1178. } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
  1179. found_needle = 1;
  1180. }
  1181. });
  1182. if (!found_needle || !circ->build_state->chosen_exit)
  1183. return;
  1184. /* write down the fingerprint of the chosen exit, not the nickname,
  1185. * because the chosen exit might not be named. */
  1186. base16_encode(fp, sizeof(fp),
  1187. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1188. /* Add this exit/hostname pair to the addressmap. */
  1189. len = strlen(conn->socks_request->address) + 1 /* '.' */ +
  1190. strlen(fp) + 1 /* '.' */ +
  1191. strlen("exit") + 1 /* '\0' */;
  1192. new_address = tor_malloc(len);
  1193. tor_snprintf(new_address, len, "%s.%s.exit",
  1194. conn->socks_request->address, fp);
  1195. addressmap_register(conn->socks_request->address, new_address,
  1196. time(NULL) + options->TrackHostExitsExpire,
  1197. ADDRMAPSRC_TRACKEXIT);
  1198. }
  1199. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1200. * begin or resolve cell as appropriate. Return values are as for
  1201. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1202. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1203. * <b>cpath</b> is NULL. */
  1204. int
  1205. connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  1206. origin_circuit_t *circ,
  1207. crypt_path_t *cpath)
  1208. {
  1209. tor_assert(conn);
  1210. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1211. conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
  1212. tor_assert(conn->socks_request);
  1213. tor_assert(circ);
  1214. tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
  1215. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1216. if (!circ->_base.timestamp_dirty)
  1217. circ->_base.timestamp_dirty = time(NULL);
  1218. link_apconn_to_circ(conn, circ, cpath);
  1219. tor_assert(conn->socks_request);
  1220. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1221. if (!conn->use_begindir)
  1222. consider_recording_trackhost(conn, circ);
  1223. if (connection_ap_handshake_send_begin(conn) < 0)
  1224. return -1;
  1225. } else {
  1226. if (connection_ap_handshake_send_resolve(conn) < 0)
  1227. return -1;
  1228. }
  1229. return 1;
  1230. }
  1231. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1232. * we don't find one: if conn cannot be handled by any known nodes,
  1233. * warn and return -1 (conn needs to die, and is maybe already marked);
  1234. * else launch new circuit (if necessary) and return 0.
  1235. * Otherwise, associate conn with a safe live circuit, do the
  1236. * right next step, and return 1.
  1237. */
  1238. /* XXXX this function should mark for close whenever it returns -1;
  1239. * its callers shouldn't have to worry about that. */
  1240. int
  1241. connection_ap_handshake_attach_circuit(edge_connection_t *conn)
  1242. {
  1243. int retval;
  1244. int conn_age;
  1245. int want_onehop;
  1246. tor_assert(conn);
  1247. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1248. tor_assert(conn->socks_request);
  1249. want_onehop = conn->want_onehop;
  1250. conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
  1251. if (conn_age >= get_options()->SocksTimeout) {
  1252. int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
  1253. LOG_INFO : LOG_NOTICE;
  1254. log_fn(severity, LD_APP,
  1255. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1256. conn_age, safe_str(conn->socks_request->address),
  1257. conn->socks_request->port);
  1258. return -1;
  1259. }
  1260. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1261. origin_circuit_t *circ=NULL;
  1262. if (conn->chosen_exit_name) {
  1263. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1264. int opt = conn->chosen_exit_optional;
  1265. if (!router && !want_onehop) {
  1266. /* We ran into this warning when trying to extend a circuit to a
  1267. * hidden service directory for which we didn't have a router
  1268. * descriptor. See flyspray task 767 for more details. We should
  1269. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1270. * directory requests as well. -KL*/
  1271. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1272. "Requested exit point '%s' is not known. %s.",
  1273. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1274. if (opt) {
  1275. conn->chosen_exit_optional = 0;
  1276. tor_free(conn->chosen_exit_name);
  1277. return 0;
  1278. }
  1279. return -1;
  1280. }
  1281. if (router && !connection_ap_can_use_exit(conn, router)) {
  1282. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1283. "Requested exit point '%s' would refuse request. %s.",
  1284. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1285. if (opt) {
  1286. conn->chosen_exit_optional = 0;
  1287. tor_free(conn->chosen_exit_name);
  1288. return 0;
  1289. }
  1290. return -1;
  1291. }
  1292. }
  1293. /* find the circuit that we should use, if there is one. */
  1294. retval = circuit_get_open_circ_or_launch(
  1295. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1296. if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
  1297. return retval;
  1298. log_debug(LD_APP|LD_CIRC,
  1299. "Attaching apconn to circ %d (stream %d sec old).",
  1300. circ->_base.n_circ_id, conn_age);
  1301. /* print the circ's path, so people can figure out which circs are
  1302. * sucking. */
  1303. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1304. /* We have found a suitable circuit for our conn. Hurray. */
  1305. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1306. } else { /* we're a rendezvous conn */
  1307. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1308. tor_assert(!conn->cpath_layer);
  1309. /* start by finding a rendezvous circuit for us */
  1310. retval = circuit_get_open_circ_or_launch(
  1311. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1312. if (retval < 0) return -1; /* failed */
  1313. if (retval > 0) {
  1314. tor_assert(rendcirc);
  1315. /* one is already established, attach */
  1316. log_info(LD_REND,
  1317. "rend joined circ %d already here. attaching. "
  1318. "(stream %d sec old)",
  1319. rendcirc->_base.n_circ_id, conn_age);
  1320. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1321. * them, since the process of rebuilding a rendezvous circ is so
  1322. * expensive. There is a tradeoffs between linkability and
  1323. * feasibility, at this point.
  1324. */
  1325. rendcirc->_base.timestamp_dirty = time(NULL);
  1326. link_apconn_to_circ(conn, rendcirc, NULL);
  1327. if (connection_ap_handshake_send_begin(conn) < 0)
  1328. return 0; /* already marked, let them fade away */
  1329. return 1;
  1330. }
  1331. if (rendcirc && (rendcirc->_base.purpose ==
  1332. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1333. log_info(LD_REND,
  1334. "pending-join circ %d already here, with intro ack. "
  1335. "Stalling. (stream %d sec old)",
  1336. rendcirc->_base.n_circ_id, conn_age);
  1337. return 0;
  1338. }
  1339. /* it's on its way. find an intro circ. */
  1340. retval = circuit_get_open_circ_or_launch(
  1341. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1342. if (retval < 0) return -1; /* failed */
  1343. if (retval > 0) {
  1344. /* one has already sent the intro. keep waiting. */
  1345. circuit_t *c = NULL;
  1346. tor_assert(introcirc);
  1347. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1348. "Stalling. (stream %d sec old)",
  1349. introcirc->_base.n_circ_id,
  1350. rendcirc ? rendcirc->_base.n_circ_id : 0,
  1351. conn_age);
  1352. /* abort parallel intro circs, if any */
  1353. for (c = global_circuitlist; c; c = c->next) {
  1354. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1355. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1356. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1357. if (oc->rend_data &&
  1358. !rend_cmp_service_ids(conn->rend_data->onion_address,
  1359. oc->rend_data->onion_address)) {
  1360. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1361. "built in parallel.");
  1362. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1363. }
  1364. }
  1365. }
  1366. return 0;
  1367. }
  1368. /* now rendcirc and introcirc are each either undefined or not finished */
  1369. if (rendcirc && introcirc &&
  1370. rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1371. log_info(LD_REND,
  1372. "ready rend circ %d already here (no intro-ack yet on "
  1373. "intro %d). (stream %d sec old)",
  1374. rendcirc->_base.n_circ_id,
  1375. introcirc->_base.n_circ_id, conn_age);
  1376. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1377. if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
  1378. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1379. "introduction. (stream %d sec old)",
  1380. introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
  1381. conn_age);
  1382. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  1383. return -1;
  1384. }
  1385. rendcirc->_base.timestamp_dirty = time(NULL);
  1386. introcirc->_base.timestamp_dirty = time(NULL);
  1387. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1388. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1389. return 0;
  1390. }
  1391. }
  1392. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1393. "Stalling conn. (%d sec old)",
  1394. introcirc ? introcirc->_base.n_circ_id : 0,
  1395. rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
  1396. return 0;
  1397. }
  1398. }