circuituse.c 46 KB

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