circuituse.c 49 KB

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