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. /********* END VARIABLES ************/
  18. static void circuit_expire_old_circuits(void);
  19. static void circuit_increment_failure_count(void);
  20. /* Return 1 if <b>circ</b> could be returned by circuit_get_best().
  21. * Else return 0.
  22. */
  23. static int
  24. circuit_is_acceptable(circuit_t *circ, connection_t *conn,
  25. int must_be_open, uint8_t purpose,
  26. int need_uptime, int need_internal,
  27. time_t now)
  28. {
  29. routerinfo_t *exitrouter;
  30. tor_assert(circ);
  31. tor_assert(conn);
  32. tor_assert(conn->socks_request);
  33. if (!CIRCUIT_IS_ORIGIN(circ))
  34. return 0; /* this circ doesn't start at us */
  35. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  36. return 0; /* ignore non-open circs */
  37. if (circ->marked_for_close)
  38. return 0;
  39. /* if this circ isn't our purpose, skip. */
  40. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  41. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  42. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  43. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  44. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  45. return 0;
  46. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  47. !must_be_open) {
  48. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  49. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  50. return 0;
  51. } else {
  52. if (purpose != circ->purpose)
  53. return 0;
  54. }
  55. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  56. if (circ->timestamp_dirty &&
  57. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  58. return 0;
  59. /* decide if this circ is suitable for this conn */
  60. /* for rend circs, circ->cpath->prev is not the last router in the
  61. * circuit, it's the magical extra bob hop. so just check the nickname
  62. * of the one we meant to finish at.
  63. */
  64. exitrouter = build_state_get_exit_router(circ->build_state);
  65. if (need_uptime && !circ->build_state->need_uptime)
  66. return 0;
  67. if (need_internal != circ->build_state->is_internal)
  68. return 0;
  69. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  70. if (!exitrouter) {
  71. debug(LD_CIRC,"Not considering circuit with unknown router.");
  72. return 0; /* this circuit is screwed and doesn't know it yet,
  73. * or is a rendezvous circuit. */
  74. }
  75. if (!connection_ap_can_use_exit(conn, exitrouter)) {
  76. /* can't exit from this router */
  77. return 0;
  78. }
  79. } else { /* not general */
  80. if (rend_cmp_service_ids(conn->rend_query, circ->rend_query)) {
  81. /* this circ is not for this conn */
  82. return 0;
  83. }
  84. }
  85. return 1;
  86. }
  87. /* Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  88. * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
  89. */
  90. static int
  91. circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
  92. {
  93. switch (purpose) {
  94. case CIRCUIT_PURPOSE_C_GENERAL:
  95. /* if it's used but less dirty it's best;
  96. * else if it's more recently created it's best
  97. */
  98. if (b->timestamp_dirty) {
  99. if (a->timestamp_dirty &&
  100. a->timestamp_dirty > b->timestamp_dirty)
  101. return 1;
  102. } else {
  103. if (a->timestamp_dirty ||
  104. b->build_state->is_internal ||
  105. a->timestamp_created > b->timestamp_created)
  106. return 1;
  107. }
  108. break;
  109. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  110. /* the closer it is to ack_wait the better it is */
  111. if (a->purpose > b->purpose)
  112. return 1;
  113. break;
  114. case CIRCUIT_PURPOSE_C_REND_JOINED:
  115. /* the closer it is to rend_joined the better it is */
  116. if (a->purpose > b->purpose)
  117. return 1;
  118. break;
  119. }
  120. return 0;
  121. }
  122. /** Find the best circ that conn can use, preferably one which is
  123. * dirty. Circ must not be too old.
  124. *
  125. * Conn must be defined.
  126. *
  127. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  128. *
  129. * circ_purpose specifies what sort of circuit we must have.
  130. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  131. *
  132. * If it's REND_JOINED and must_be_open==0, then return the closest
  133. * rendezvous-purposed circuit that you can find.
  134. *
  135. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  136. * closest introduce-purposed circuit that you can find.
  137. */
  138. static circuit_t *
  139. circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose,
  140. int need_uptime, int need_internal)
  141. {
  142. circuit_t *circ, *best=NULL;
  143. time_t now = time(NULL);
  144. tor_assert(conn);
  145. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  146. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  147. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  148. for (circ=global_circuitlist;circ;circ = circ->next) {
  149. if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
  150. need_uptime,need_internal,now))
  151. continue;
  152. /* now this is an acceptable circ to hand back. but that doesn't
  153. * mean it's the *best* circ to hand back. try to decide.
  154. */
  155. if (!best || circuit_is_better(circ,best,purpose))
  156. best = circ;
  157. }
  158. return best;
  159. }
  160. /** If we find a circuit that isn't open yet and was born this many
  161. * seconds ago, then assume something went wrong, and cull it.
  162. */
  163. #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
  164. /** Close all circuits that start at us, aren't open, and were born
  165. * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
  166. */
  167. void
  168. circuit_expire_building(time_t now)
  169. {
  170. circuit_t *victim, *circ = global_circuitlist;
  171. time_t cutoff = now - MIN_SECONDS_BEFORE_EXPIRING_CIRC;
  172. while (circ) {
  173. victim = circ;
  174. circ = circ->next;
  175. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  176. victim->timestamp_created > cutoff || /* Not old enough to expire */
  177. victim->marked_for_close) /* don't mess with marked circs */
  178. continue;
  179. #if 0
  180. /* some debug logs, to help track bugs */
  181. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  182. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  183. if (!victim->timestamp_dirty)
  184. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d)."
  185. "(clean).",
  186. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  187. victim->purpose, victim->build_state->chosen_exit_name,
  188. victim->n_circ_id);
  189. else
  190. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). "
  191. "%d secs since dirty.",
  192. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  193. victim->purpose, victim->build_state->chosen_exit_name,
  194. victim->n_circ_id,
  195. (int)(now - victim->timestamp_dirty));
  196. }
  197. #endif
  198. /* if circ is !open, or if it's open but purpose is a non-finished
  199. * intro or rend, then mark it for close */
  200. if (victim->state == CIRCUIT_STATE_OPEN) {
  201. switch (victim->purpose) {
  202. default: /* most open circuits can be left alone. */
  203. continue; /* yes, continue inside a switch refers to the nearest
  204. * enclosing loop. C is smart. */
  205. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  206. case CIRCUIT_PURPOSE_C_INTRODUCING:
  207. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  208. break; /* too old, need to die */
  209. case CIRCUIT_PURPOSE_C_REND_READY:
  210. /* it's a rend_ready circ -- has it already picked a query? */
  211. /* c_rend_ready circs measure age since timestamp_dirty,
  212. * because that's set when they switch purposes
  213. */
  214. if (!victim->rend_query[0] || victim->timestamp_dirty > cutoff)
  215. continue;
  216. break;
  217. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  218. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  219. /* rend and intro circs become dirty each time they
  220. * make an introduction attempt. so timestamp_dirty
  221. * will reflect the time since the last attempt.
  222. */
  223. if (victim->timestamp_dirty > cutoff)
  224. continue;
  225. break;
  226. }
  227. }
  228. if (victim->n_conn)
  229. info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  230. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  231. victim->state, circuit_state_to_string(victim->state),
  232. victim->purpose);
  233. else
  234. info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  235. victim->n_circ_id, victim->state,
  236. circuit_state_to_string(victim->state), victim->purpose);
  237. circuit_log_path(LOG_INFO,LD_CIRC,victim);
  238. circuit_mark_for_close(victim);
  239. }
  240. }
  241. /** Remove any elements in <b>needed_ports</b> that are handled by an
  242. * open or in-progress circuit.
  243. */
  244. void
  245. circuit_remove_handled_ports(smartlist_t *needed_ports)
  246. {
  247. int i;
  248. uint16_t *port;
  249. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  250. port = smartlist_get(needed_ports, i);
  251. tor_assert(*port);
  252. if (circuit_stream_is_being_handled(NULL, *port, 2)) {
  253. // debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  254. smartlist_del(needed_ports, i--);
  255. tor_free(port);
  256. } else {
  257. debug(LD_CIRC,"Port %d is not handled.", *port);
  258. }
  259. }
  260. }
  261. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  262. * will have an acceptable exit node for exit stream <b>conn</b> if it
  263. * is defined, else for "*:port".
  264. * Else return 0.
  265. */
  266. int
  267. circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min)
  268. {
  269. circuit_t *circ;
  270. routerinfo_t *exitrouter;
  271. int num=0;
  272. time_t now = time(NULL);
  273. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  274. conn ? conn->socks_request->port : port);
  275. for (circ=global_circuitlist;circ;circ = circ->next) {
  276. if (CIRCUIT_IS_ORIGIN(circ) &&
  277. !circ->marked_for_close &&
  278. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  279. !circ->build_state->is_internal &&
  280. (!circ->timestamp_dirty ||
  281. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  282. exitrouter = build_state_get_exit_router(circ->build_state);
  283. if (exitrouter &&
  284. (!need_uptime || circ->build_state->need_uptime)) {
  285. int ok;
  286. if (conn) {
  287. ok = connection_ap_can_use_exit(conn, exitrouter);
  288. } else {
  289. addr_policy_result_t r = router_compare_addr_to_addr_policy(
  290. 0, port, exitrouter->exit_policy);
  291. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  292. }
  293. if (ok) {
  294. if (++num >= min)
  295. return 1;
  296. }
  297. }
  298. }
  299. }
  300. return 0;
  301. }
  302. /** Don't keep more than 10 unused open circuits around. */
  303. #define MAX_UNUSED_OPEN_CIRCUITS 12
  304. /** Figure out how many circuits we have open that are clean. Make
  305. * sure it's enough for all the upcoming behaviors we predict we'll have.
  306. * But if we have too many, close the not-so-useful ones.
  307. */
  308. static void
  309. circuit_predict_and_launch_new(void)
  310. {
  311. circuit_t *circ;
  312. int num=0, num_internal=0, num_uptime_internal=0;
  313. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  314. int port_needs_uptime=0, port_needs_capacity=1;
  315. time_t now = time(NULL);
  316. /* First, count how many of each type of circuit we have already. */
  317. for (circ=global_circuitlist;circ;circ = circ->next) {
  318. if (!CIRCUIT_IS_ORIGIN(circ))
  319. continue;
  320. if (circ->marked_for_close)
  321. continue; /* don't mess with marked circs */
  322. if (circ->timestamp_dirty)
  323. continue; /* only count clean circs */
  324. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  325. continue; /* only pay attention to general-purpose circs */
  326. num++;
  327. if (circ->build_state->is_internal)
  328. num_internal++;
  329. if (circ->build_state->need_uptime && circ->build_state->is_internal)
  330. num_uptime_internal++;
  331. }
  332. /* If that's enough, then stop now. */
  333. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  334. return; /* we already have many, making more probably will hurt */
  335. /* Second, see if we need any more exit circuits. */
  336. /* check if we know of a port that's been requested recently
  337. * and no circuit is currently available that can handle it. */
  338. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  339. &port_needs_capacity)) {
  340. info(LD_CIRC,"Have %d clean circs (%d internal), need another exit circ.",
  341. num, num_internal);
  342. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  343. port_needs_uptime, port_needs_capacity, 0);
  344. return;
  345. }
  346. /* Third, see if we need any more hidden service (server) circuits. */
  347. if (num_rend_services() && num_uptime_internal < 3) {
  348. info(LD_CIRC,"Have %d clean circs (%d internal), need another internal "
  349. "circ for my hidden service.",
  350. num, num_internal);
  351. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  352. 1, 1, 1);
  353. return;
  354. }
  355. /* Fourth, see if we need any more hidden service (client) circuits. */
  356. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  357. &hidserv_needs_capacity) &&
  358. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  359. num_internal<2)) {
  360. info(LD_CIRC,"Have %d clean circs (%d uptime-internal, %d internal), need "
  361. " another hidserv circ.", num, num_uptime_internal, num_internal);
  362. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  363. hidserv_needs_uptime, hidserv_needs_capacity, 1);
  364. return;
  365. }
  366. }
  367. /** Build a new test circuit every 5 minutes */
  368. #define TESTING_CIRCUIT_INTERVAL 300
  369. /** This function is called once a second. Its job is to make sure
  370. * all services we offer have enough circuits available. Some
  371. * services just want enough circuits for current tasks, whereas
  372. * others want a minimum set of idle circuits hanging around.
  373. */
  374. void
  375. circuit_build_needed_circs(time_t now)
  376. {
  377. static long time_to_new_circuit = 0;
  378. /* launch a new circ for any pending streams that need one */
  379. connection_ap_attach_pending();
  380. /* make sure any hidden services have enough intro points */
  381. if (router_have_minimum_dir_info())
  382. rend_services_introduce();
  383. if (time_to_new_circuit < now) {
  384. circuit_reset_failure_count(1);
  385. time_to_new_circuit = now + get_options()->NewCircuitPeriod;
  386. if (proxy_mode(get_options()))
  387. addressmap_clean(now);
  388. circuit_expire_old_circuits();
  389. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  390. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  391. if (get_options()->RunTesting &&
  392. circ &&
  393. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  394. log_fn(LOG_INFO,"Creating a new testing circuit.");
  395. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
  396. }
  397. #endif
  398. }
  399. circuit_predict_and_launch_new();
  400. }
  401. /** If the stream <b>conn</b> is a member of any of the linked
  402. * lists of <b>circ</b>, then remove it from the list.
  403. */
  404. void
  405. circuit_detach_stream(circuit_t *circ, connection_t *conn)
  406. {
  407. connection_t *prevconn;
  408. tor_assert(circ);
  409. tor_assert(conn);
  410. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  411. conn->on_circuit = NULL;
  412. if (conn == circ->p_streams) {
  413. circ->p_streams = conn->next_stream;
  414. return;
  415. }
  416. if (conn == circ->n_streams) {
  417. circ->n_streams = conn->next_stream;
  418. return;
  419. }
  420. if (conn == circ->resolving_streams) {
  421. circ->resolving_streams = conn->next_stream;
  422. return;
  423. }
  424. for (prevconn = circ->p_streams;
  425. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  426. prevconn = prevconn->next_stream)
  427. ;
  428. if (prevconn && prevconn->next_stream) {
  429. prevconn->next_stream = conn->next_stream;
  430. return;
  431. }
  432. for (prevconn = circ->n_streams;
  433. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  434. prevconn = prevconn->next_stream)
  435. ;
  436. if (prevconn && prevconn->next_stream) {
  437. prevconn->next_stream = conn->next_stream;
  438. return;
  439. }
  440. for (prevconn = circ->resolving_streams;
  441. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  442. prevconn = prevconn->next_stream)
  443. ;
  444. if (prevconn && prevconn->next_stream) {
  445. prevconn->next_stream = conn->next_stream;
  446. return;
  447. }
  448. err(LD_BUG,"edge conn not in circuit's list?");
  449. tor_assert(0); /* should never get here */
  450. }
  451. /** Notify the global circuit list that <b>conn</b> is about to be
  452. * removed and then freed.
  453. *
  454. * If it's an OR conn, then mark-for-close all the circuits that use
  455. * that conn.
  456. *
  457. * If it's an edge conn, then detach it from its circ, so we don't
  458. * try to reference it later.
  459. */
  460. void
  461. circuit_about_to_close_connection(connection_t *conn)
  462. {
  463. /* currently, we assume it's too late to flush conn's buf here.
  464. * down the road, maybe we'll consider that eof doesn't mean can't-write
  465. */
  466. switch (conn->type) {
  467. case CONN_TYPE_OR: {
  468. /* Inform any pending (not attached) circs that they should give up. */
  469. circuit_n_conn_done(conn, 0);
  470. /* Now close all the attached circuits on it. */
  471. circuit_unlink_all_from_or_conn(conn);
  472. return;
  473. }
  474. case CONN_TYPE_AP:
  475. case CONN_TYPE_EXIT: {
  476. circuit_t *circ;
  477. /* It's an edge conn. Need to remove it from the linked list of
  478. * conn's for this circuit. Confirm that 'end' relay command has
  479. * been sent. But don't kill the circuit.
  480. */
  481. circ = circuit_get_by_edge_conn(conn);
  482. if (!circ)
  483. return;
  484. circuit_detach_stream(circ, conn);
  485. }
  486. } /* end switch */
  487. }
  488. /** Find each circuit that has been dirty for too long, and has
  489. * no streams on it: mark it for close.
  490. */
  491. static void
  492. circuit_expire_old_circuits(void)
  493. {
  494. circuit_t *circ;
  495. time_t now = time(NULL);
  496. for (circ = global_circuitlist; circ; circ = circ->next) {
  497. if (circ->marked_for_close)
  498. continue;
  499. /* If the circuit has been dirty for too long, and there are no streams
  500. * on it, mark it for close.
  501. */
  502. if (circ->timestamp_dirty &&
  503. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
  504. CIRCUIT_IS_ORIGIN(circ) &&
  505. !circ->p_streams /* nothing attached */ ) {
  506. debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
  507. circ->n_circ_id, (int)(now - circ->timestamp_dirty),
  508. circ->purpose);
  509. /* (only general and purpose_c circs can get dirty) */
  510. tor_assert(!circ->n_streams);
  511. tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
  512. circuit_mark_for_close(circ);
  513. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  514. circ->state == CIRCUIT_STATE_OPEN &&
  515. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  516. #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
  517. if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
  518. debug(LD_CIRC,"Closing circuit that has been unused for %d seconds.",
  519. (int)(now - circ->timestamp_created));
  520. circuit_mark_for_close(circ);
  521. }
  522. }
  523. }
  524. }
  525. /** A testing circuit has completed. Take whatever stats we want. */
  526. static void
  527. circuit_testing_opened(circuit_t *circ)
  528. {
  529. /* For now, we only use testing circuits to see if our ORPort is
  530. reachable. But we remember reachability in onionskin_answer(),
  531. so there's no need to record anything here. Just close the circ. */
  532. circuit_mark_for_close(circ);
  533. }
  534. /** A testing circuit has failed to build. Take whatever stats we want. */
  535. static void
  536. circuit_testing_failed(circuit_t *circ, int at_last_hop)
  537. {
  538. #if 0
  539. routerinfo_t *me = router_get_my_routerinfo();
  540. if (!at_last_hop)
  541. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  542. else
  543. #endif
  544. info(LD_GENERAL,"Our testing circuit (to see if your ORPort is reachable) "
  545. "has failed. I'll try again later.");
  546. }
  547. /** The circuit <b>circ</b> has just become open. Take the next
  548. * step: for rendezvous circuits, we pass circ to the appropriate
  549. * function in rendclient or rendservice. For general circuits, we
  550. * call connection_ap_attach_pending, which looks for pending streams
  551. * that could use circ.
  552. */
  553. void
  554. circuit_has_opened(circuit_t *circ)
  555. {
  556. control_event_circuit_status(circ, CIRC_EVENT_BUILT);
  557. switch (circ->purpose) {
  558. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  559. rend_client_rendcirc_has_opened(circ);
  560. connection_ap_attach_pending();
  561. break;
  562. case CIRCUIT_PURPOSE_C_INTRODUCING:
  563. rend_client_introcirc_has_opened(circ);
  564. break;
  565. case CIRCUIT_PURPOSE_C_GENERAL:
  566. /* Tell any AP connections that have been waiting for a new
  567. * circuit that one is ready. */
  568. connection_ap_attach_pending();
  569. break;
  570. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  571. /* at Bob, waiting for introductions */
  572. rend_service_intro_has_opened(circ);
  573. break;
  574. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  575. /* at Bob, connecting to rend point */
  576. rend_service_rendezvous_has_opened(circ);
  577. break;
  578. case CIRCUIT_PURPOSE_TESTING:
  579. circuit_testing_opened(circ);
  580. break;
  581. default:
  582. err(LD_BUG,"unhandled purpose %d",circ->purpose);
  583. tor_assert(0);
  584. }
  585. }
  586. /** Called whenever a circuit could not be successfully built.
  587. */
  588. void
  589. circuit_build_failed(circuit_t *circ)
  590. {
  591. /* we should examine circ and see if it failed because of
  592. * the last hop or an earlier hop. then use this info below.
  593. */
  594. int failed_at_last_hop = 0;
  595. /* If the last hop isn't open, and the second-to-last is, we failed
  596. * at the last hop. */
  597. if (circ->cpath &&
  598. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  599. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  600. failed_at_last_hop = 1;
  601. }
  602. if (circ->cpath &&
  603. circ->cpath->state != CPATH_STATE_OPEN) {
  604. /* We failed at the first hop. If there's an OR connection
  605. to blame, blame it. */
  606. if (circ->n_conn) {
  607. info(LD_OR, "Our circuit failed to get a response from the first hop "
  608. "(%s:%d). I'm going to try to rotate to a better connection.",
  609. circ->n_conn->address, circ->n_conn->port);
  610. circ->n_conn->is_obsolete = 1;
  611. helper_node_set_status(circ->n_conn->identity_digest, 0);
  612. }
  613. }
  614. switch (circ->purpose) {
  615. case CIRCUIT_PURPOSE_C_GENERAL:
  616. if (circ->state != CIRCUIT_STATE_OPEN) {
  617. /* If we never built the circuit, note it as a failure. */
  618. /* Note that we can't just check circ->cpath here, because if
  619. * circuit-building failed immediately, it won't be set yet. */
  620. circuit_increment_failure_count();
  621. }
  622. break;
  623. case CIRCUIT_PURPOSE_TESTING:
  624. circuit_testing_failed(circ, failed_at_last_hop);
  625. break;
  626. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  627. /* at Bob, waiting for introductions */
  628. if (circ->state != CIRCUIT_STATE_OPEN) {
  629. circuit_increment_failure_count();
  630. }
  631. /* no need to care here, because bob will rebuild intro
  632. * points periodically. */
  633. break;
  634. case CIRCUIT_PURPOSE_C_INTRODUCING:
  635. /* at Alice, connecting to intro point */
  636. /* Don't increment failure count, since Bob may have picked
  637. * the introduction point maliciously */
  638. /* Alice will pick a new intro point when this one dies, if
  639. * the stream in question still cares. No need to act here. */
  640. break;
  641. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  642. /* at Alice, waiting for Bob */
  643. if (circ->state != CIRCUIT_STATE_OPEN) {
  644. circuit_increment_failure_count();
  645. }
  646. /* Alice will pick a new rend point when this one dies, if
  647. * the stream in question still cares. No need to act here. */
  648. break;
  649. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  650. /* at Bob, connecting to rend point */
  651. /* Don't increment failure count, since Alice may have picked
  652. * the rendezvous point maliciously */
  653. info(LD_REND,
  654. "Couldn't connect to Alice's chosen rend point %s (%s hop failed).",
  655. build_state_get_exit_nickname(circ->build_state),
  656. failed_at_last_hop?"last":"non-last");
  657. rend_service_relaunch_rendezvous(circ);
  658. break;
  659. default:
  660. /* Other cases are impossible, since this function is only called with
  661. * unbuilt circuits. */
  662. tor_assert(0);
  663. }
  664. }
  665. /** Number of consecutive failures so far; should only be touched by
  666. * circuit_launch_new and circuit_*_failure_count.
  667. */
  668. static int n_circuit_failures = 0;
  669. static int did_circs_fail_last_period = 0;
  670. /** Don't retry launching a new circuit if we try this many times with no
  671. * success. */
  672. #define MAX_CIRCUIT_FAILURES 5
  673. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  674. * details on arguments. */
  675. circuit_t *
  676. circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
  677. int need_uptime, int need_capacity, int internal)
  678. {
  679. circuit_t *circ;
  680. extend_info_t *info = NULL;
  681. if (exit)
  682. info = extend_info_from_router(exit);
  683. circ = circuit_launch_by_extend_info(
  684. purpose, info, need_uptime, need_capacity, internal);
  685. if (info)
  686. extend_info_free(info);
  687. return circ;
  688. }
  689. /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
  690. * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
  691. * choose among routers with high uptime. If <b>need_capacity</b> is true,
  692. * choose among routers with high bandwidth. If <b>internal</b> is true, the
  693. * last hop need not be an exit node. Return the newly allocated circuit on
  694. * success, or NULL on failure. */
  695. circuit_t *
  696. circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info,
  697. int need_uptime, int need_capacity, int internal)
  698. {
  699. circuit_t *circ;
  700. if (!router_have_minimum_dir_info()) {
  701. debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  702. "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 (!router_have_minimum_dir_info()) {
  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 router_have_minimum_dir_info 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. }