circuituse.c 45 KB

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