circuituse.c 49 KB

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