circuituse.c 43 KB

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