circuituse.c 42 KB

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