circuituse.c 43 KB

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