circuituse.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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. case CIRCUIT_PURPOSE_OR:
  200. case CIRCUIT_PURPOSE_INTRO_POINT:
  201. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  202. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  203. /* OR-side. We can't actually reach this point because of the
  204. * IS_ORIGIN test above. */
  205. continue; /* yes, continue inside a switch refers to the nearest
  206. * enclosing loop. C is smart. */
  207. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  208. case CIRCUIT_PURPOSE_C_INTRODUCING:
  209. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  210. break;
  211. case CIRCUIT_PURPOSE_C_REND_READY:
  212. /* it's a rend_ready circ -- has it already picked a query? */
  213. if (!victim->rend_query[0] && victim->timestamp_dirty > cutoff)
  214. continue;
  215. break;
  216. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  217. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  218. /* c_rend_ready circs measure age since timestamp_dirty,
  219. * because that's set when they switch purposes
  220. */
  221. /* rend and intro circs become dirty each time they
  222. * make an introduction attempt. so timestamp_dirty
  223. * will reflect the time since the last attempt.
  224. */
  225. if (victim->timestamp_dirty > cutoff)
  226. continue;
  227. break;
  228. }
  229. }
  230. if (victim->n_conn)
  231. info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  232. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  233. victim->state, circuit_state_to_string(victim->state), victim->purpose);
  234. else
  235. info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  236. victim->n_circ_id, victim->state,
  237. circuit_state_to_string(victim->state), victim->purpose);
  238. circuit_log_path(LOG_INFO,LD_CIRC,victim);
  239. circuit_mark_for_close(victim);
  240. }
  241. }
  242. /** Remove any elements in <b>needed_ports</b> that are handled by an
  243. * open or in-progress circuit.
  244. */
  245. void
  246. circuit_remove_handled_ports(smartlist_t *needed_ports)
  247. {
  248. int i;
  249. uint16_t *port;
  250. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  251. port = smartlist_get(needed_ports, i);
  252. tor_assert(*port);
  253. if (circuit_stream_is_being_handled(NULL, *port, 2)) {
  254. // debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  255. smartlist_del(needed_ports, i--);
  256. tor_free(port);
  257. } else {
  258. debug(LD_CIRC,"Port %d is not handled.", *port);
  259. }
  260. }
  261. }
  262. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  263. * will have an acceptable exit node for exit stream <b>conn</b> if it
  264. * is defined, else for "*:port".
  265. * Else return 0.
  266. */
  267. int
  268. circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min)
  269. {
  270. circuit_t *circ;
  271. routerinfo_t *exitrouter;
  272. int num=0;
  273. time_t now = time(NULL);
  274. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  275. conn ? conn->socks_request->port : port);
  276. for (circ=global_circuitlist;circ;circ = circ->next) {
  277. if (CIRCUIT_IS_ORIGIN(circ) &&
  278. !circ->marked_for_close &&
  279. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  280. !circ->build_state->is_internal &&
  281. (!circ->timestamp_dirty ||
  282. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now)) {
  283. exitrouter = build_state_get_exit_router(circ->build_state);
  284. if (exitrouter &&
  285. (!need_uptime || circ->build_state->need_uptime)) {
  286. int ok;
  287. if (conn) {
  288. ok = connection_ap_can_use_exit(conn, exitrouter);
  289. } else {
  290. addr_policy_result_t r =
  291. router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy);
  292. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  293. }
  294. if (ok) {
  295. if (++num >= min)
  296. return 1;
  297. }
  298. }
  299. }
  300. }
  301. return 0;
  302. }
  303. /** Don't keep more than 10 unused open circuits around. */
  304. #define MAX_UNUSED_OPEN_CIRCUITS 12
  305. /** Figure out how many circuits we have open that are clean. Make
  306. * sure it's enough for all the upcoming behaviors we predict we'll have.
  307. * But if we have too many, close the not-so-useful ones.
  308. */
  309. static void
  310. circuit_predict_and_launch_new(void)
  311. {
  312. circuit_t *circ;
  313. int num=0, num_internal=0, num_uptime_internal=0;
  314. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  315. int port_needs_uptime=0, port_needs_capacity=1;
  316. time_t now = time(NULL);
  317. /* First, count how many of each type of circuit we have already. */
  318. for (circ=global_circuitlist;circ;circ = circ->next) {
  319. if (!CIRCUIT_IS_ORIGIN(circ))
  320. continue;
  321. if (circ->marked_for_close)
  322. continue; /* don't mess with marked circs */
  323. if (circ->timestamp_dirty)
  324. continue; /* only count clean circs */
  325. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  326. continue; /* only pay attention to general-purpose circs */
  327. num++;
  328. if (circ->build_state->is_internal)
  329. num_internal++;
  330. if (circ->build_state->need_uptime && circ->build_state->is_internal)
  331. num_uptime_internal++;
  332. }
  333. /* If that's enough, then stop now. */
  334. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  335. return; /* we already have many, making more probably will hurt */
  336. /* Second, see if we need any more exit circuits. */
  337. /* check if we know of a port that's been requested recently
  338. * and no circuit is currently available that can handle it. */
  339. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  340. &port_needs_capacity)) {
  341. info(LD_CIRC,"Have %d clean circs (%d internal), need another exit circ.",
  342. num, num_internal);
  343. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  344. port_needs_uptime, port_needs_capacity, 0);
  345. return;
  346. }
  347. /* Third, see if we need any more hidden service (server) circuits. */
  348. if (num_rend_services() && num_uptime_internal < 3) {
  349. info(LD_CIRC,"Have %d clean circs (%d internal), need another internal 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),"
  361. " need 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 (has_fetched_directory)
  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. smartlist_t *circs;
  469. /* Inform any pending (not attached) circs that they should give up. */
  470. circuit_n_conn_done(conn, 0);
  471. circs = circuit_get_all_on_orconn(conn);
  472. /* Now close all the attached circuits on it. */
  473. SMARTLIST_FOREACH(circs, circuit_t *, circ, {
  474. if (circ->n_conn == conn)
  475. /* it's closing in front of us */
  476. circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
  477. if (circ->p_conn == conn)
  478. /* it's closing behind us */
  479. circuit_set_circid_orconn(circ, 0, NULL, P_CONN_CHANGED);
  480. circuit_mark_for_close(circ);
  481. });
  482. smartlist_free(circs);
  483. return;
  484. }
  485. case CONN_TYPE_AP:
  486. case CONN_TYPE_EXIT: {
  487. circuit_t *circ;
  488. /* It's an edge conn. Need to remove it from the linked list of
  489. * conn's for this circuit. Confirm that 'end' relay command has
  490. * been sent. But don't kill the circuit.
  491. */
  492. circ = circuit_get_by_edge_conn(conn);
  493. if (!circ)
  494. return;
  495. circuit_detach_stream(circ, conn);
  496. }
  497. } /* end switch */
  498. }
  499. /** Find each circuit that has been dirty for too long, and has
  500. * no streams on it: mark it for close.
  501. */
  502. static void
  503. circuit_expire_old_circuits(void)
  504. {
  505. circuit_t *circ;
  506. time_t now = time(NULL);
  507. for (circ = global_circuitlist; circ; circ = circ->next) {
  508. if (circ->marked_for_close)
  509. continue;
  510. /* If the circuit has been dirty for too long, and there are no streams
  511. * on it, mark it for close.
  512. */
  513. if (circ->timestamp_dirty &&
  514. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
  515. CIRCUIT_IS_ORIGIN(circ) &&
  516. !circ->p_streams /* nothing attached */ ) {
  517. debug(LD_CIRC,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",
  518. circ->n_circ_id, (int)(now - circ->timestamp_dirty), circ->purpose);
  519. /* (only general and purpose_c circs can get dirty) */
  520. tor_assert(!circ->n_streams);
  521. tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
  522. circuit_mark_for_close(circ);
  523. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  524. circ->state == CIRCUIT_STATE_OPEN &&
  525. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  526. #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
  527. if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
  528. debug(LD_CIRC,"Closing circuit that has been unused for %d seconds.",
  529. (int)(now - circ->timestamp_created));
  530. circuit_mark_for_close(circ);
  531. }
  532. }
  533. }
  534. }
  535. /** A testing circuit has completed. Take whatever stats we want. */
  536. static void
  537. circuit_testing_opened(circuit_t *circ)
  538. {
  539. /* For now, we only use testing circuits to see if our ORPort is
  540. reachable. But we remember reachability in onionskin_answer(),
  541. so there's no need to record anything here. Just close the circ. */
  542. circuit_mark_for_close(circ);
  543. }
  544. /** A testing circuit has failed to build. Take whatever stats we want. */
  545. static void
  546. circuit_testing_failed(circuit_t *circ, int at_last_hop)
  547. {
  548. #if 0
  549. routerinfo_t *me = router_get_my_routerinfo();
  550. if (!at_last_hop)
  551. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  552. else
  553. #endif
  554. info(LD_GENERAL,"Our testing circuit (to see if your ORPort is reachable) has failed. I'll try again later.");
  555. }
  556. /** The circuit <b>circ</b> has just become open. Take the next
  557. * step: for rendezvous circuits, we pass circ to the appropriate
  558. * function in rendclient or rendservice. For general circuits, we
  559. * call connection_ap_attach_pending, which looks for pending streams
  560. * that could use circ.
  561. */
  562. void
  563. circuit_has_opened(circuit_t *circ)
  564. {
  565. control_event_circuit_status(circ, CIRC_EVENT_BUILT);
  566. switch (circ->purpose) {
  567. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  568. rend_client_rendcirc_has_opened(circ);
  569. connection_ap_attach_pending();
  570. break;
  571. case CIRCUIT_PURPOSE_C_INTRODUCING:
  572. rend_client_introcirc_has_opened(circ);
  573. break;
  574. case CIRCUIT_PURPOSE_C_GENERAL:
  575. /* Tell any AP connections that have been waiting for a new
  576. * circuit that one is ready. */
  577. connection_ap_attach_pending();
  578. break;
  579. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  580. /* at Bob, waiting for introductions */
  581. rend_service_intro_has_opened(circ);
  582. break;
  583. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  584. /* at Bob, connecting to rend point */
  585. rend_service_rendezvous_has_opened(circ);
  586. break;
  587. case CIRCUIT_PURPOSE_TESTING:
  588. circuit_testing_opened(circ);
  589. break;
  590. default:
  591. err(LD_BUG,"unhandled purpose %d",circ->purpose);
  592. tor_assert(0);
  593. }
  594. }
  595. /** Called whenever a circuit could not be successfully built.
  596. */
  597. void
  598. circuit_build_failed(circuit_t *circ)
  599. {
  600. /* we should examine circ and see if it failed because of
  601. * the last hop or an earlier hop. then use this info below.
  602. */
  603. int failed_at_last_hop = 0;
  604. /* If the last hop isn't open, and the second-to-last is, we failed
  605. * at the last hop. */
  606. if (circ->cpath &&
  607. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  608. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  609. failed_at_last_hop = 1;
  610. }
  611. if (circ->cpath &&
  612. circ->cpath->state != CPATH_STATE_OPEN) {
  613. /* We failed at the first hop. If there's an OR connection
  614. to blame, blame it. */
  615. if (circ->n_conn) {
  616. 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.",
  617. circ->n_conn->address, circ->n_conn->port);
  618. circ->n_conn->is_obsolete = 1;
  619. }
  620. }
  621. switch (circ->purpose) {
  622. case CIRCUIT_PURPOSE_C_GENERAL:
  623. if (circ->state != CIRCUIT_STATE_OPEN) {
  624. /* If we never built the circuit, note it as a failure. */
  625. /* Note that we can't just check circ->cpath here, because if
  626. * circuit-building failed immediately, it won't be set yet. */
  627. circuit_increment_failure_count();
  628. }
  629. break;
  630. case CIRCUIT_PURPOSE_TESTING:
  631. circuit_testing_failed(circ, failed_at_last_hop);
  632. break;
  633. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  634. /* at Bob, waiting for introductions */
  635. if (circ->state != CIRCUIT_STATE_OPEN) {
  636. circuit_increment_failure_count();
  637. }
  638. /* no need to care here, because bob will rebuild intro
  639. * points periodically. */
  640. break;
  641. case CIRCUIT_PURPOSE_C_INTRODUCING:
  642. /* at Alice, connecting to intro point */
  643. /* Don't increment failure count, since Bob may have picked
  644. * the introduction point maliciously */
  645. /* Alice will pick a new intro point when this one dies, if
  646. * the stream in question still cares. No need to act here. */
  647. break;
  648. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  649. /* at Alice, waiting for Bob */
  650. if (circ->state != CIRCUIT_STATE_OPEN) {
  651. circuit_increment_failure_count();
  652. }
  653. /* Alice will pick a new rend point when this one dies, if
  654. * the stream in question still cares. No need to act here. */
  655. break;
  656. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  657. /* at Bob, connecting to rend point */
  658. /* Don't increment failure count, since Alice may have picked
  659. * the rendezvous point maliciously */
  660. info(LD_REND,
  661. "Couldn't connect to Alice's chosen rend point %s (%s hop failed).",
  662. build_state_get_exit_nickname(circ->build_state),
  663. failed_at_last_hop?"last":"non-last");
  664. rend_service_relaunch_rendezvous(circ);
  665. break;
  666. default:
  667. /* Other cases are impossible, since this function is only called with
  668. * unbuilt circuits. */
  669. tor_assert(0);
  670. }
  671. }
  672. /** Number of consecutive failures so far; should only be touched by
  673. * circuit_launch_new and circuit_*_failure_count.
  674. */
  675. static int n_circuit_failures = 0;
  676. static int did_circs_fail_last_period = 0;
  677. /** Don't retry launching a new circuit if we try this many times with no
  678. * success. */
  679. #define MAX_CIRCUIT_FAILURES 5
  680. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  681. * details on arguments. */
  682. circuit_t *
  683. circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
  684. int need_uptime, int need_capacity, int internal)
  685. {
  686. circuit_t *circ;
  687. extend_info_t *info = NULL;
  688. if (exit)
  689. info = extend_info_from_router(exit);
  690. circ = circuit_launch_by_extend_info(purpose, info, need_uptime, need_capacity,
  691. internal);
  692. if (info)
  693. extend_info_free(info);
  694. return circ;
  695. }
  696. /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
  697. * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
  698. * choose among routers with high uptime. If <b>need_capacity</b> is true,
  699. * choose among routers with high bandwidth. If <b>internal</b> is true, the
  700. * last hop need not be an exit node. Return the newly allocated circuit on
  701. * success, or NULL on failure. */
  702. circuit_t *
  703. circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info,
  704. int need_uptime, int need_capacity, int internal)
  705. {
  706. circuit_t *circ;
  707. if (!has_fetched_directory) {
  708. debug(LD_CIRC,"Haven't fetched directory yet; canceling circuit launch.");
  709. return NULL;
  710. }
  711. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  712. purpose != CIRCUIT_PURPOSE_TESTING) {
  713. /* see if there are appropriate circs available to cannibalize. */
  714. circ = circuit_find_to_cannibalize(CIRCUIT_PURPOSE_C_GENERAL, extend_info,
  715. need_uptime, need_capacity, internal);
  716. if (circ) {
  717. info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
  718. build_state_get_exit_nickname(circ->build_state), purpose);
  719. circ->purpose = purpose;
  720. /* reset the birth date of this circ, else expire_building
  721. * will see it and think it's been trying to build since it
  722. * began. */
  723. circ->timestamp_created = time(NULL);
  724. switch (purpose) {
  725. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  726. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  727. /* it's ready right now */
  728. break;
  729. case CIRCUIT_PURPOSE_C_INTRODUCING:
  730. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  731. case CIRCUIT_PURPOSE_C_GENERAL:
  732. /* need to add a new hop */
  733. tor_assert(extend_info);
  734. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  735. return NULL;
  736. break;
  737. default:
  738. warn(LD_BUG, "Bug: unexpected purpose %d when cannibalizing a circ.", purpose);
  739. tor_fragile_assert();
  740. return NULL;
  741. }
  742. return circ;
  743. }
  744. }
  745. if (did_circs_fail_last_period &&
  746. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  747. /* too many failed circs in a row. don't try. */
  748. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  749. return NULL;
  750. }
  751. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  752. return circuit_establish_circuit(purpose, extend_info,
  753. need_uptime, need_capacity, internal);
  754. }
  755. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  756. * details on arguments. */
  757. circuit_t *
  758. circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
  759. int need_uptime, int need_capacity, int internal)
  760. {
  761. routerinfo_t *router = NULL;
  762. if (exit_nickname) {
  763. router = router_get_by_nickname(exit_nickname, 1);
  764. if (!router) {
  765. /*XXXXNM domain? */
  766. warn(LD_GENERAL, "No such OR as '%s'", exit_nickname);
  767. return NULL;
  768. }
  769. }
  770. return circuit_launch_by_router(purpose, router,
  771. need_uptime, need_capacity, internal);
  772. }
  773. /** Record another failure at opening a general circuit. When we have
  774. * too many, we'll stop trying for the remainder of this minute.
  775. */
  776. static void
  777. circuit_increment_failure_count(void)
  778. {
  779. ++n_circuit_failures;
  780. debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  781. }
  782. /** Reset the failure count for opening general circuits. This means
  783. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  784. * stopping again.
  785. */
  786. void
  787. circuit_reset_failure_count(int timeout)
  788. {
  789. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  790. did_circs_fail_last_period = 1;
  791. else
  792. did_circs_fail_last_period = 0;
  793. n_circuit_failures = 0;
  794. }
  795. /** Find an open circ that we're happy with: return 1. If there isn't
  796. * one, and there isn't one on the way, launch one and return 0. If it
  797. * will never work, return -1.
  798. *
  799. * Write the found or in-progress or launched circ into *circp.
  800. */
  801. static int
  802. circuit_get_open_circ_or_launch(connection_t *conn,
  803. uint8_t desired_circuit_purpose,
  804. circuit_t **circp)
  805. {
  806. circuit_t *circ;
  807. int is_resolve;
  808. int need_uptime, need_internal;
  809. tor_assert(conn);
  810. tor_assert(circp);
  811. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  812. is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
  813. need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  814. conn->socks_request->port);
  815. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  816. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  817. need_uptime, need_internal);
  818. if (circ) {
  819. *circp = circ;
  820. return 1; /* we're happy */
  821. }
  822. if (!has_fetched_directory) {
  823. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  824. notice(LD_APP|LD_DIR,"Application request when we're believed to be offline. Optimistically trying directory fetches again.");
  825. router_reset_status_download_failures();
  826. router_reset_descriptor_download_failures();
  827. update_networkstatus_downloads(time(NULL));
  828. /* XXXX011 NM This should be a generic "retry all directory fetches". */
  829. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1); /*XXXX011NM*/
  830. }
  831. /* the stream will be dealt with when has_fetched_directory becomes
  832. * 1, or when all directory attempts fail and directory_all_unreachable()
  833. * kills it.
  834. */
  835. return 0;
  836. }
  837. /* Do we need to check exit policy? */
  838. if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
  839. struct in_addr in;
  840. uint32_t addr = 0;
  841. if (tor_inet_aton(conn->socks_request->address, &in))
  842. addr = ntohl(in.s_addr);
  843. if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
  844. need_uptime)) {
  845. notice(LD_APP,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  846. safe_str(conn->socks_request->address), conn->socks_request->port);
  847. return -1;
  848. }
  849. }
  850. /* is one already on the way? */
  851. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  852. need_uptime, need_internal);
  853. if (!circ) {
  854. extend_info_t *extend_info=NULL;
  855. uint8_t new_circ_purpose;
  856. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  857. /* need to pick an intro point */
  858. extend_info = rend_client_get_random_intro(conn->rend_query);
  859. if (!extend_info) {
  860. info(LD_REND,"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.", circ->n_circ_id);
  922. apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
  923. apconn->next_stream = circ->p_streams;
  924. apconn->on_circuit = circ;
  925. /* assert_connection_ok(conn, time(NULL)); */
  926. circ->p_streams = apconn;
  927. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  928. tor_assert(circ->cpath);
  929. tor_assert(circ->cpath->prev);
  930. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  931. apconn->cpath_layer = circ->cpath->prev;
  932. }
  933. /** If an exit wasn't specifically chosen, save the history for future
  934. * use */
  935. static void
  936. consider_recording_trackhost(connection_t *conn, circuit_t *circ)
  937. {
  938. int found_needle = 0;
  939. char *str;
  940. or_options_t *options = get_options();
  941. size_t len;
  942. char *new_address;
  943. /* Search the addressmap for this conn's destination. */
  944. /* If he's not in the address map.. */
  945. if (!options->TrackHostExits ||
  946. addressmap_already_mapped(conn->socks_request->address))
  947. return; /* nothing to track, or already mapped */
  948. SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
  949. if (cp[0] == '.') { /* match end */
  950. /* XXX strstr is probably really bad here */
  951. if ((str = strstr(conn->socks_request->address, &cp[1]))) {
  952. if (str == conn->socks_request->address
  953. || strcmp(str, &cp[1]) == 0) {
  954. found_needle = 1;
  955. }
  956. }
  957. } else if (strcmp(cp, conn->socks_request->address) == 0) {
  958. found_needle = 1;
  959. }
  960. });
  961. if (!found_needle || !circ->build_state->chosen_exit)
  962. return;
  963. /* Add this exit/hostname pair to the addressmap. */
  964. len = strlen(conn->socks_request->address) + 1 /* '.' */ +
  965. strlen(circ->build_state->chosen_exit->nickname) + 1 /* '.' */ +
  966. strlen("exit") + 1 /* '\0' */;
  967. new_address = tor_malloc(len);
  968. tor_snprintf(new_address, len, "%s.%s.exit",
  969. conn->socks_request->address,
  970. circ->build_state->chosen_exit->nickname);
  971. addressmap_register(conn->socks_request->address, new_address,
  972. time(NULL) + options->TrackHostExitsExpire);
  973. }
  974. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and
  975. * send a begin or resolve cell as appropriate. Return values are as
  976. * for connection_ap_handshake_attach_circuit. */
  977. int
  978. connection_ap_handshake_attach_chosen_circuit(connection_t *conn,
  979. circuit_t *circ)
  980. {
  981. tor_assert(conn);
  982. tor_assert(conn->type == CONN_TYPE_AP);
  983. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  984. conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  985. tor_assert(conn->socks_request);
  986. tor_assert(circ);
  987. tor_assert(circ->state == CIRCUIT_STATE_OPEN);
  988. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  989. if (!circ->timestamp_dirty)
  990. circ->timestamp_dirty = time(NULL);
  991. link_apconn_to_circ(conn, circ);
  992. tor_assert(conn->socks_request);
  993. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  994. consider_recording_trackhost(conn, circ);
  995. if (connection_ap_handshake_send_begin(conn, circ)<0)
  996. return -1;
  997. } else {
  998. if (connection_ap_handshake_send_resolve(conn, circ)<0)
  999. return -1;
  1000. }
  1001. return 1;
  1002. }
  1003. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1004. * we don't find one: if conn cannot be handled by any known nodes,
  1005. * warn and return -1 (conn needs to die);
  1006. * else launch new circuit (if necessary) and return 0.
  1007. * Otherwise, associate conn with a safe live circuit, do the
  1008. * right next step, and return 1.
  1009. */
  1010. int
  1011. connection_ap_handshake_attach_circuit(connection_t *conn)
  1012. {
  1013. int retval;
  1014. int conn_age;
  1015. tor_assert(conn);
  1016. tor_assert(conn->type == CONN_TYPE_AP);
  1017. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1018. tor_assert(conn->socks_request);
  1019. conn_age = time(NULL) - conn->timestamp_created;
  1020. if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
  1021. notice(LD_APP,"Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1022. conn_age, safe_str(conn->socks_request->address),
  1023. conn->socks_request->port);
  1024. return -1;
  1025. }
  1026. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1027. circuit_t *circ=NULL;
  1028. if (conn->chosen_exit_name) {
  1029. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1030. if (!router) {
  1031. warn(LD_APP,"Requested exit point '%s' is not known. Closing.",
  1032. conn->chosen_exit_name);
  1033. return -1;
  1034. }
  1035. if (!connection_ap_can_use_exit(conn, router)) {
  1036. warn(LD_APP, "Requested exit point '%s' would refuse request. Closing.",
  1037. conn->chosen_exit_name);
  1038. return -1;
  1039. }
  1040. }
  1041. /* find the circuit that we should use, if there is one. */
  1042. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1043. if (retval < 1)
  1044. return retval;
  1045. debug(LD_APP|LD_CIRC,"Attaching apconn to circ %d (stream %d sec old).",
  1046. circ->n_circ_id, conn_age);
  1047. /* here, print the circ's path. so people can figure out which circs are sucking. */
  1048. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1049. /* We have found a suitable circuit for our conn. Hurray. */
  1050. return connection_ap_handshake_attach_chosen_circuit(conn, circ);
  1051. } else { /* we're a rendezvous conn */
  1052. circuit_t *rendcirc=NULL, *introcirc=NULL;
  1053. tor_assert(!conn->cpath_layer);
  1054. /* start by finding a rendezvous circuit for us */
  1055. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1056. if (retval < 0) return -1; /* failed */
  1057. if (retval > 0) {
  1058. tor_assert(rendcirc);
  1059. /* one is already established, attach */
  1060. info(LD_REND,
  1061. "rend joined circ %d already here. attaching. (stream %d sec old)",
  1062. rendcirc->n_circ_id, conn_age);
  1063. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1064. * them, since the process of rebuilding a rendezvous circ is so
  1065. * expensive. There is a tradeoffs between linkability and
  1066. * feasibility, at this point.
  1067. */
  1068. rendcirc->timestamp_dirty = time(NULL);
  1069. link_apconn_to_circ(conn, rendcirc);
  1070. if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
  1071. return 0; /* already marked, let them fade away */
  1072. return 1;
  1073. }
  1074. if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  1075. info(LD_REND,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
  1076. return 0;
  1077. }
  1078. /* it's on its way. find an intro circ. */
  1079. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1080. if (retval < 0) return -1; /* failed */
  1081. if (retval > 0) {
  1082. /* one has already sent the intro. keep waiting. */
  1083. tor_assert(introcirc);
  1084. info(LD_REND,
  1085. "Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
  1086. introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  1087. return 0;
  1088. }
  1089. /* now rendcirc and introcirc are each either undefined or not finished */
  1090. if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1091. info(LD_REND,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
  1092. rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
  1093. tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1094. if (introcirc->state == CIRCUIT_STATE_OPEN) {
  1095. info(LD_REND,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
  1096. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  1097. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  1098. return -1;
  1099. }
  1100. rendcirc->timestamp_dirty = time(NULL);
  1101. introcirc->timestamp_dirty = time(NULL);
  1102. assert_circuit_ok(rendcirc);
  1103. assert_circuit_ok(introcirc);
  1104. return 0;
  1105. }
  1106. }
  1107. info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
  1108. introcirc ? introcirc->n_circ_id : 0,
  1109. rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  1110. return 0;
  1111. }
  1112. }