circuituse.c 41 KB

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