circuituse.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2009, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuituse.c
  8. * \brief Launch the right sort of circuits and attach streams to them.
  9. **/
  10. #include "or.h"
  11. /********* START VARIABLES **********/
  12. extern circuit_t *global_circuitlist; /* from circuitlist.c */
  13. /********* END VARIABLES ************/
  14. static void circuit_expire_old_circuits(time_t now);
  15. static void circuit_increment_failure_count(void);
  16. long int lround(double x);
  17. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  18. * Else return 0.
  19. */
  20. static int
  21. circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
  22. int must_be_open, uint8_t purpose,
  23. int need_uptime, int need_internal,
  24. time_t now)
  25. {
  26. routerinfo_t *exitrouter;
  27. cpath_build_state_t *build_state;
  28. tor_assert(circ);
  29. tor_assert(conn);
  30. tor_assert(conn->socks_request);
  31. if (!CIRCUIT_IS_ORIGIN(circ))
  32. return 0; /* this circ doesn't start at us */
  33. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  34. return 0; /* ignore non-open circs */
  35. if (circ->marked_for_close)
  36. return 0;
  37. /* if this circ isn't our purpose, skip. */
  38. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  39. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  40. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  41. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  42. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  43. return 0;
  44. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  45. !must_be_open) {
  46. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  47. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  48. return 0;
  49. } else {
  50. if (purpose != circ->purpose)
  51. return 0;
  52. }
  53. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  54. if (circ->timestamp_dirty &&
  55. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  56. return 0;
  57. /* decide if this circ is suitable for this conn */
  58. /* for rend circs, circ->cpath->prev is not the last router in the
  59. * circuit, it's the magical extra bob hop. so just check the nickname
  60. * of the one we meant to finish at.
  61. */
  62. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  63. exitrouter = build_state_get_exit_router(build_state);
  64. if (need_uptime && !build_state->need_uptime)
  65. return 0;
  66. if (need_internal != build_state->is_internal)
  67. return 0;
  68. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  69. if (!exitrouter && !build_state->onehop_tunnel) {
  70. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  71. return 0; /* this circuit is screwed and doesn't know it yet,
  72. * or is a rendezvous circuit. */
  73. }
  74. if (build_state->onehop_tunnel) {
  75. if (!conn->want_onehop) {
  76. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  77. return 0;
  78. }
  79. tor_assert(conn->chosen_exit_name);
  80. if (build_state->chosen_exit) {
  81. char digest[DIGEST_LEN];
  82. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  83. return 0; /* broken digest, we don't want it */
  84. if (memcmp(digest, build_state->chosen_exit->identity_digest,
  85. DIGEST_LEN))
  86. return 0; /* this is a circuit to somewhere else */
  87. if (tor_digest_is_zero(digest)) {
  88. /* we don't know the digest; have to compare addr:port */
  89. tor_addr_t addr;
  90. int r = tor_addr_from_str(&addr, conn->socks_request->address);
  91. if (r < 0 ||
  92. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  93. build_state->chosen_exit->port != conn->socks_request->port)
  94. return 0;
  95. }
  96. }
  97. } else {
  98. if (conn->want_onehop) {
  99. /* don't use three-hop circuits -- that could hurt our anonymity. */
  100. return 0;
  101. }
  102. }
  103. if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter)) {
  104. /* can't exit from this router */
  105. return 0;
  106. }
  107. } else { /* not general */
  108. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  109. if ((conn->rend_data && !ocirc->rend_data) ||
  110. (!conn->rend_data && ocirc->rend_data) ||
  111. (conn->rend_data && ocirc->rend_data &&
  112. rend_cmp_service_ids(conn->rend_data->onion_address,
  113. ocirc->rend_data->onion_address))) {
  114. /* this circ is not for this conn */
  115. return 0;
  116. }
  117. }
  118. return 1;
  119. }
  120. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  121. * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
  122. */
  123. static int
  124. circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
  125. {
  126. switch (purpose) {
  127. case CIRCUIT_PURPOSE_C_GENERAL:
  128. /* if it's used but less dirty it's best;
  129. * else if it's more recently created it's best
  130. */
  131. if (b->timestamp_dirty) {
  132. if (a->timestamp_dirty &&
  133. a->timestamp_dirty > b->timestamp_dirty)
  134. return 1;
  135. } else {
  136. if (a->timestamp_dirty ||
  137. a->timestamp_created > b->timestamp_created)
  138. return 1;
  139. if (CIRCUIT_IS_ORIGIN(b) &&
  140. TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
  141. return 1;
  142. }
  143. break;
  144. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  145. /* the closer it is to ack_wait the better it is */
  146. if (a->purpose > b->purpose)
  147. return 1;
  148. break;
  149. case CIRCUIT_PURPOSE_C_REND_JOINED:
  150. /* the closer it is to rend_joined the better it is */
  151. if (a->purpose > b->purpose)
  152. return 1;
  153. break;
  154. }
  155. return 0;
  156. }
  157. /** Find the best circ that conn can use, preferably one which is
  158. * dirty. Circ must not be too old.
  159. *
  160. * Conn must be defined.
  161. *
  162. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  163. *
  164. * circ_purpose specifies what sort of circuit we must have.
  165. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  166. *
  167. * If it's REND_JOINED and must_be_open==0, then return the closest
  168. * rendezvous-purposed circuit that you can find.
  169. *
  170. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  171. * closest introduce-purposed circuit that you can find.
  172. */
  173. static origin_circuit_t *
  174. circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
  175. int need_uptime, int need_internal)
  176. {
  177. circuit_t *circ, *best=NULL;
  178. time_t now = time(NULL);
  179. int intro_going_on_but_too_old = 0;
  180. tor_assert(conn);
  181. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  182. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  183. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  184. for (circ=global_circuitlist;circ;circ = circ->next) {
  185. if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
  186. need_uptime,need_internal,now))
  187. continue;
  188. /* XXX022 make this 15 be a function of circuit finishing times we've
  189. * seen lately, a la Fallon Chen's GSoC work -RD */
  190. #define REND_PARALLEL_INTRO_DELAY 15
  191. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  192. !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
  193. circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
  194. intro_going_on_but_too_old = 1;
  195. continue;
  196. }
  197. /* now this is an acceptable circ to hand back. but that doesn't
  198. * mean it's the *best* circ to hand back. try to decide.
  199. */
  200. if (!best || circuit_is_better(circ,best,purpose))
  201. best = circ;
  202. }
  203. if (!best && intro_going_on_but_too_old)
  204. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  205. "right now, but it has already taken quite a while. Starting "
  206. "one in parallel.");
  207. return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
  208. }
  209. /** Check whether, according to the policies in <b>options</b>, the
  210. * circuit <b>circ</b> makes sense. */
  211. /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
  212. int
  213. circuit_conforms_to_options(const origin_circuit_t *circ,
  214. const or_options_t *options)
  215. {
  216. const crypt_path_t *cpath, *cpath_next = NULL;
  217. for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
  218. cpath = cpath_next) {
  219. cpath_next = cpath->next;
  220. if (routerset_contains_extendinfo(options->ExcludeNodes,
  221. cpath->extend_info))
  222. return 0;
  223. if (cpath->next == circ->cpath) {
  224. /* This is apparently the exit node. */
  225. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  226. cpath->extend_info))
  227. return 0;
  228. }
  229. }
  230. return 1;
  231. }
  232. /** Close all circuits that start at us, aren't open, and were born
  233. * at least CircuitBuildTimeout seconds ago.
  234. */
  235. void
  236. circuit_expire_building(time_t now)
  237. {
  238. circuit_t *victim, *next_circ = global_circuitlist;
  239. /* circ_times.timeout is BUILD_TIMEOUT_INITIAL_VALUE if we haven't
  240. * decided on a customized one yet */
  241. time_t general_cutoff = now - lround(circ_times.timeout_ms/1000);
  242. time_t begindir_cutoff = now - lround(circ_times.timeout_ms/2000);
  243. time_t introcirc_cutoff = begindir_cutoff;
  244. cpath_build_state_t *build_state;
  245. while (next_circ) {
  246. time_t cutoff;
  247. victim = next_circ;
  248. next_circ = next_circ->next;
  249. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  250. victim->marked_for_close) /* don't mess with marked circs */
  251. continue;
  252. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  253. if (build_state && build_state->onehop_tunnel)
  254. cutoff = begindir_cutoff;
  255. else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  256. cutoff = introcirc_cutoff;
  257. else
  258. cutoff = general_cutoff;
  259. if (victim->timestamp_created > cutoff)
  260. continue; /* it's still young, leave it alone */
  261. #if 0
  262. /* some debug logs, to help track bugs */
  263. if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  264. victim->timestamp_created <= introcirc_cutoff &&
  265. victim->timestamp_created > general_cutoff)
  266. log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
  267. "would not have done if it had been a general circuit.");
  268. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  269. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  270. if (!victim->timestamp_dirty)
  271. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
  272. "(clean).",
  273. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  274. victim->purpose, victim->build_state->chosen_exit_name,
  275. victim->n_circ_id);
  276. else
  277. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
  278. "%d secs since dirty.",
  279. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  280. victim->purpose, victim->build_state->chosen_exit_name,
  281. victim->n_circ_id,
  282. (int)(now - victim->timestamp_dirty));
  283. }
  284. #endif
  285. /* if circ is !open, or if it's open but purpose is a non-finished
  286. * intro or rend, then mark it for close */
  287. if (victim->state == CIRCUIT_STATE_OPEN) {
  288. switch (victim->purpose) {
  289. default: /* most open circuits can be left alone. */
  290. continue; /* yes, continue inside a switch refers to the nearest
  291. * enclosing loop. C is smart. */
  292. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  293. case CIRCUIT_PURPOSE_C_INTRODUCING:
  294. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  295. break; /* too old, need to die */
  296. case CIRCUIT_PURPOSE_C_REND_READY:
  297. /* it's a rend_ready circ -- has it already picked a query? */
  298. /* c_rend_ready circs measure age since timestamp_dirty,
  299. * because that's set when they switch purposes
  300. */
  301. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  302. victim->timestamp_dirty > cutoff)
  303. continue;
  304. break;
  305. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  306. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  307. /* rend and intro circs become dirty each time they
  308. * make an introduction attempt. so timestamp_dirty
  309. * will reflect the time since the last attempt.
  310. */
  311. if (victim->timestamp_dirty > cutoff)
  312. continue;
  313. break;
  314. }
  315. } else { /* circuit not open, consider recording failure as timeout */
  316. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
  317. TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
  318. if (circuit_build_times_add_timeout(&circ_times, first_hop_succeeded,
  319. victim->timestamp_created))
  320. circuit_build_times_set_timeout(&circ_times);
  321. }
  322. if (victim->n_conn)
  323. log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  324. victim->n_conn->_base.address, victim->n_conn->_base.port,
  325. victim->n_circ_id,
  326. victim->state, circuit_state_to_string(victim->state),
  327. victim->purpose);
  328. else
  329. log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  330. victim->n_circ_id, victim->state,
  331. circuit_state_to_string(victim->state), victim->purpose);
  332. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  333. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  334. }
  335. }
  336. /** Remove any elements in <b>needed_ports</b> that are handled by an
  337. * open or in-progress circuit.
  338. */
  339. void
  340. circuit_remove_handled_ports(smartlist_t *needed_ports)
  341. {
  342. int i;
  343. uint16_t *port;
  344. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  345. port = smartlist_get(needed_ports, i);
  346. tor_assert(*port);
  347. if (circuit_stream_is_being_handled(NULL, *port,
  348. MIN_CIRCUITS_HANDLING_STREAM)) {
  349. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  350. smartlist_del(needed_ports, i--);
  351. tor_free(port);
  352. } else {
  353. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  354. }
  355. }
  356. }
  357. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  358. * will have an acceptable exit node for exit stream <b>conn</b> if it
  359. * is defined, else for "*:port".
  360. * Else return 0.
  361. */
  362. int
  363. circuit_stream_is_being_handled(edge_connection_t *conn,
  364. uint16_t port, int min)
  365. {
  366. circuit_t *circ;
  367. routerinfo_t *exitrouter;
  368. int num=0;
  369. time_t now = time(NULL);
  370. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  371. conn ? conn->socks_request->port : port);
  372. for (circ=global_circuitlist;circ;circ = circ->next) {
  373. if (CIRCUIT_IS_ORIGIN(circ) &&
  374. !circ->marked_for_close &&
  375. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  376. (!circ->timestamp_dirty ||
  377. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  378. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  379. if (build_state->is_internal || build_state->onehop_tunnel)
  380. continue;
  381. exitrouter = build_state_get_exit_router(build_state);
  382. if (exitrouter && (!need_uptime || build_state->need_uptime)) {
  383. int ok;
  384. if (conn) {
  385. ok = connection_ap_can_use_exit(conn, exitrouter);
  386. } else {
  387. addr_policy_result_t r = compare_addr_to_addr_policy(
  388. 0, port, exitrouter->exit_policy);
  389. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  390. }
  391. if (ok) {
  392. if (++num >= min)
  393. return 1;
  394. }
  395. }
  396. }
  397. }
  398. return 0;
  399. }
  400. /** Don't keep more than this many unused open circuits around. */
  401. #define MAX_UNUSED_OPEN_CIRCUITS 14
  402. /** Figure out how many circuits we have open that are clean. Make
  403. * sure it's enough for all the upcoming behaviors we predict we'll have.
  404. * But put an upper bound on the total number of circuits.
  405. */
  406. static void
  407. circuit_predict_and_launch_new(void)
  408. {
  409. circuit_t *circ;
  410. int num=0, num_internal=0, num_uptime_internal=0;
  411. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  412. int port_needs_uptime=0, port_needs_capacity=1;
  413. time_t now = time(NULL);
  414. int flags = 0;
  415. /* First, count how many of each type of circuit we have already. */
  416. for (circ=global_circuitlist;circ;circ = circ->next) {
  417. cpath_build_state_t *build_state;
  418. if (!CIRCUIT_IS_ORIGIN(circ))
  419. continue;
  420. if (circ->marked_for_close)
  421. continue; /* don't mess with marked circs */
  422. if (circ->timestamp_dirty)
  423. continue; /* only count clean circs */
  424. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  425. continue; /* only pay attention to general-purpose circs */
  426. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  427. if (build_state->onehop_tunnel)
  428. continue;
  429. num++;
  430. if (build_state->is_internal)
  431. num_internal++;
  432. if (build_state->need_uptime && build_state->is_internal)
  433. num_uptime_internal++;
  434. }
  435. /* If that's enough, then stop now. */
  436. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  437. return; /* we already have many, making more probably will hurt */
  438. /* Second, see if we need any more exit circuits. */
  439. /* check if we know of a port that's been requested recently
  440. * and no circuit is currently available that can handle it. */
  441. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  442. &port_needs_capacity)) {
  443. if (port_needs_uptime)
  444. flags |= CIRCLAUNCH_NEED_UPTIME;
  445. if (port_needs_capacity)
  446. flags |= CIRCLAUNCH_NEED_CAPACITY;
  447. log_info(LD_CIRC,
  448. "Have %d clean circs (%d internal), need another exit circ.",
  449. num, num_internal);
  450. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  451. return;
  452. }
  453. /* Third, see if we need any more hidden service (server) circuits. */
  454. if (num_rend_services() && num_uptime_internal < 3) {
  455. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  456. CIRCLAUNCH_IS_INTERNAL);
  457. log_info(LD_CIRC,
  458. "Have %d clean circs (%d internal), need another internal "
  459. "circ for my hidden service.",
  460. num, num_internal);
  461. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  462. return;
  463. }
  464. /* Fourth, see if we need any more hidden service (client) circuits. */
  465. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  466. &hidserv_needs_capacity) &&
  467. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  468. num_internal<2)) {
  469. if (hidserv_needs_uptime)
  470. flags |= CIRCLAUNCH_NEED_UPTIME;
  471. if (hidserv_needs_capacity)
  472. flags |= CIRCLAUNCH_NEED_CAPACITY;
  473. flags |= CIRCLAUNCH_IS_INTERNAL;
  474. log_info(LD_CIRC,
  475. "Have %d clean circs (%d uptime-internal, %d internal), need"
  476. " another hidden service circ.",
  477. num, num_uptime_internal, num_internal);
  478. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  479. return;
  480. }
  481. /* Finally, check to see if we still need more circuits to learn
  482. * a good build timeout. But if we're close to our max number we
  483. * want, don't do another -- we want to leave a few slots open so
  484. * we can still build circuits preemptively as needed. */
  485. if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
  486. circuit_build_times_needs_circuits_now(&circ_times)) {
  487. flags = CIRCLAUNCH_NEED_CAPACITY;
  488. log_info(LD_CIRC,
  489. "Have %d clean circs need another buildtime test circ.", num);
  490. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
  491. return;
  492. }
  493. }
  494. /** Build a new test circuit every 5 minutes */
  495. #define TESTING_CIRCUIT_INTERVAL 300
  496. /** This function is called once a second, if router_have_min_dir_info() is
  497. * true. Its job is to make sure all services we offer have enough circuits
  498. * available. Some services just want enough circuits for current tasks,
  499. * whereas others want a minimum set of idle circuits hanging around.
  500. */
  501. void
  502. circuit_build_needed_circs(time_t now)
  503. {
  504. static time_t time_to_new_circuit = 0;
  505. or_options_t *options = get_options();
  506. /* launch a new circ for any pending streams that need one */
  507. connection_ap_attach_pending();
  508. /* make sure any hidden services have enough intro points */
  509. rend_services_introduce();
  510. if (time_to_new_circuit < now) {
  511. circuit_reset_failure_count(1);
  512. time_to_new_circuit = now + options->NewCircuitPeriod;
  513. if (proxy_mode(get_options()))
  514. addressmap_clean(now);
  515. circuit_expire_old_circuits(now);
  516. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  517. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  518. if (get_options()->RunTesting &&
  519. circ &&
  520. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  521. log_fn(LOG_INFO,"Creating a new testing circuit.");
  522. circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
  523. }
  524. #endif
  525. }
  526. if (!options->DisablePredictedCircuits)
  527. circuit_predict_and_launch_new();
  528. }
  529. /** If the stream <b>conn</b> is a member of any of the linked
  530. * lists of <b>circ</b>, then remove it from the list.
  531. */
  532. void
  533. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  534. {
  535. edge_connection_t *prevconn;
  536. tor_assert(circ);
  537. tor_assert(conn);
  538. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  539. conn->on_circuit = NULL;
  540. if (CIRCUIT_IS_ORIGIN(circ)) {
  541. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  542. if (conn == origin_circ->p_streams) {
  543. origin_circ->p_streams = conn->next_stream;
  544. return;
  545. }
  546. for (prevconn = origin_circ->p_streams;
  547. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  548. prevconn = prevconn->next_stream)
  549. ;
  550. if (prevconn && prevconn->next_stream) {
  551. prevconn->next_stream = conn->next_stream;
  552. return;
  553. }
  554. } else {
  555. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  556. if (conn == or_circ->n_streams) {
  557. or_circ->n_streams = conn->next_stream;
  558. return;
  559. }
  560. if (conn == or_circ->resolving_streams) {
  561. or_circ->resolving_streams = conn->next_stream;
  562. return;
  563. }
  564. for (prevconn = or_circ->n_streams;
  565. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  566. prevconn = prevconn->next_stream)
  567. ;
  568. if (prevconn && prevconn->next_stream) {
  569. prevconn->next_stream = conn->next_stream;
  570. return;
  571. }
  572. for (prevconn = or_circ->resolving_streams;
  573. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  574. prevconn = prevconn->next_stream)
  575. ;
  576. if (prevconn && prevconn->next_stream) {
  577. prevconn->next_stream = conn->next_stream;
  578. return;
  579. }
  580. }
  581. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  582. /* Don't give an error here; it's harmless. */
  583. tor_fragile_assert();
  584. }
  585. /** If we haven't yet decided on a good timeout value for circuit
  586. * building, we close idles circuits aggressively so we can get more
  587. * data points. */
  588. #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
  589. /** Find each circuit that has been unused for too long, or dirty
  590. * for too long and has no streams on it: mark it for close.
  591. */
  592. static void
  593. circuit_expire_old_circuits(time_t now)
  594. {
  595. circuit_t *circ;
  596. time_t cutoff;
  597. if (circuit_build_times_needs_circuits(&circ_times)) {
  598. /* Circuits should be shorter lived if we need more of them
  599. * for learning a good build timeout */
  600. cutoff = now - IDLE_TIMEOUT_WHILE_LEARNING;
  601. } else {
  602. cutoff = now - get_options()->CircuitIdleTimeout;
  603. }
  604. for (circ = global_circuitlist; circ; circ = circ->next) {
  605. if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
  606. continue;
  607. /* If the circuit has been dirty for too long, and there are no streams
  608. * on it, mark it for close.
  609. */
  610. if (circ->timestamp_dirty &&
  611. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
  612. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  613. log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, "
  614. "purpose %d)",
  615. circ->n_circ_id, (int)(now - circ->timestamp_dirty),
  616. circ->purpose);
  617. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  618. } else if (!circ->timestamp_dirty &&
  619. circ->state == CIRCUIT_STATE_OPEN &&
  620. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  621. if (circ->timestamp_created < cutoff) {
  622. log_debug(LD_CIRC,
  623. "Closing circuit that has been unused for %d seconds.",
  624. (int)(now - circ->timestamp_created));
  625. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  626. }
  627. }
  628. }
  629. }
  630. /** Number of testing circuits we want open before testing our bandwidth. */
  631. #define NUM_PARALLEL_TESTING_CIRCS 4
  632. /** True iff we've ever had enough testing circuits open to test our
  633. * bandwidth. */
  634. static int have_performed_bandwidth_test = 0;
  635. /** Reset have_performed_bandwidth_test, so we'll start building
  636. * testing circuits again so we can exercise our bandwidth. */
  637. void
  638. reset_bandwidth_test(void)
  639. {
  640. have_performed_bandwidth_test = 0;
  641. }
  642. /** Return 1 if we've already exercised our bandwidth, or if we
  643. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  644. * established or on the way. Else return 0.
  645. */
  646. int
  647. circuit_enough_testing_circs(void)
  648. {
  649. circuit_t *circ;
  650. int num = 0;
  651. if (have_performed_bandwidth_test)
  652. return 1;
  653. for (circ = global_circuitlist; circ; circ = circ->next) {
  654. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  655. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  656. circ->state == CIRCUIT_STATE_OPEN)
  657. num++;
  658. }
  659. return num >= NUM_PARALLEL_TESTING_CIRCS;
  660. }
  661. /** A testing circuit has completed. Take whatever stats we want.
  662. * Noticing reachability is taken care of in onionskin_answer(),
  663. * so there's no need to record anything here. But if we still want
  664. * to do the bandwidth test, and we now have enough testing circuits
  665. * open, do it.
  666. */
  667. static void
  668. circuit_testing_opened(origin_circuit_t *circ)
  669. {
  670. if (have_performed_bandwidth_test ||
  671. !check_whether_orport_reachable()) {
  672. /* either we've already done everything we want with testing circuits,
  673. * or this testing circuit became open due to a fluke, e.g. we picked
  674. * a last hop where we already had the connection open due to an
  675. * outgoing local circuit. */
  676. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  677. } else if (circuit_enough_testing_circs()) {
  678. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  679. have_performed_bandwidth_test = 1;
  680. } else
  681. consider_testing_reachability(1, 0);
  682. }
  683. /** A testing circuit has failed to build. Take whatever stats we want. */
  684. static void
  685. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  686. {
  687. if (server_mode(get_options()) && check_whether_orport_reachable())
  688. return;
  689. log_info(LD_GENERAL,
  690. "Our testing circuit (to see if your ORPort is reachable) "
  691. "has failed. I'll try again later.");
  692. /* These aren't used yet. */
  693. (void)circ;
  694. (void)at_last_hop;
  695. }
  696. /** The circuit <b>circ</b> has just become open. Take the next
  697. * step: for rendezvous circuits, we pass circ to the appropriate
  698. * function in rendclient or rendservice. For general circuits, we
  699. * call connection_ap_attach_pending, which looks for pending streams
  700. * that could use circ.
  701. */
  702. void
  703. circuit_has_opened(origin_circuit_t *circ)
  704. {
  705. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  706. switch (TO_CIRCUIT(circ)->purpose) {
  707. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  708. rend_client_rendcirc_has_opened(circ);
  709. connection_ap_attach_pending();
  710. break;
  711. case CIRCUIT_PURPOSE_C_INTRODUCING:
  712. rend_client_introcirc_has_opened(circ);
  713. break;
  714. case CIRCUIT_PURPOSE_C_GENERAL:
  715. /* Tell any AP connections that have been waiting for a new
  716. * circuit that one is ready. */
  717. connection_ap_attach_pending();
  718. break;
  719. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  720. /* at Bob, waiting for introductions */
  721. rend_service_intro_has_opened(circ);
  722. break;
  723. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  724. /* at Bob, connecting to rend point */
  725. rend_service_rendezvous_has_opened(circ);
  726. break;
  727. case CIRCUIT_PURPOSE_TESTING:
  728. circuit_testing_opened(circ);
  729. break;
  730. /* default:
  731. * This won't happen in normal operation, but might happen if the
  732. * controller did it. Just let it slide. */
  733. }
  734. }
  735. /** Called whenever a circuit could not be successfully built.
  736. */
  737. void
  738. circuit_build_failed(origin_circuit_t *circ)
  739. {
  740. /* we should examine circ and see if it failed because of
  741. * the last hop or an earlier hop. then use this info below.
  742. */
  743. int failed_at_last_hop = 0;
  744. /* If the last hop isn't open, and the second-to-last is, we failed
  745. * at the last hop. */
  746. if (circ->cpath &&
  747. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  748. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  749. failed_at_last_hop = 1;
  750. }
  751. if (circ->cpath &&
  752. circ->cpath->state != CPATH_STATE_OPEN) {
  753. /* We failed at the first hop. If there's an OR connection
  754. * to blame, blame it. Also, avoid this relay for a while, and
  755. * fail any one-hop directory fetches destined for it. */
  756. const char *n_conn_id = circ->cpath->extend_info->identity_digest;
  757. if (circ->_base.n_conn) {
  758. or_connection_t *n_conn = circ->_base.n_conn;
  759. log_info(LD_OR,
  760. "Our circuit failed to get a response from the first hop "
  761. "(%s:%d). I'm going to try to rotate to a better connection.",
  762. n_conn->_base.address, n_conn->_base.port);
  763. n_conn->is_bad_for_new_circs = 1;
  764. } else {
  765. log_info(LD_OR,
  766. "Our circuit died before the first hop with no connection");
  767. }
  768. if (n_conn_id) {
  769. entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
  770. /* if there are any one-hop streams waiting on this circuit, fail
  771. * them now so they can retry elsewhere. */
  772. connection_ap_fail_onehop(n_conn_id, circ->build_state);
  773. }
  774. }
  775. switch (circ->_base.purpose) {
  776. case CIRCUIT_PURPOSE_C_GENERAL:
  777. /* If we never built the circuit, note it as a failure. */
  778. circuit_increment_failure_count();
  779. if (failed_at_last_hop) {
  780. /* Make sure any streams that demand our last hop as their exit
  781. * know that it's unlikely to happen. */
  782. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  783. }
  784. break;
  785. case CIRCUIT_PURPOSE_TESTING:
  786. circuit_testing_failed(circ, failed_at_last_hop);
  787. break;
  788. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  789. /* at Bob, waiting for introductions */
  790. if (circ->_base.state != CIRCUIT_STATE_OPEN) {
  791. circuit_increment_failure_count();
  792. }
  793. /* no need to care here, because bob will rebuild intro
  794. * points periodically. */
  795. break;
  796. case CIRCUIT_PURPOSE_C_INTRODUCING:
  797. /* at Alice, connecting to intro point */
  798. /* Don't increment failure count, since Bob may have picked
  799. * the introduction point maliciously */
  800. /* Alice will pick a new intro point when this one dies, if
  801. * the stream in question still cares. No need to act here. */
  802. break;
  803. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  804. /* at Alice, waiting for Bob */
  805. circuit_increment_failure_count();
  806. /* Alice will pick a new rend point when this one dies, if
  807. * the stream in question still cares. No need to act here. */
  808. break;
  809. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  810. /* at Bob, connecting to rend point */
  811. /* Don't increment failure count, since Alice may have picked
  812. * the rendezvous point maliciously */
  813. log_info(LD_REND,
  814. "Couldn't connect to Alice's chosen rend point %s "
  815. "(%s hop failed).",
  816. escaped(build_state_get_exit_nickname(circ->build_state)),
  817. failed_at_last_hop?"last":"non-last");
  818. rend_service_relaunch_rendezvous(circ);
  819. break;
  820. /* default:
  821. * This won't happen in normal operation, but might happen if the
  822. * controller did it. Just let it slide. */
  823. }
  824. }
  825. /** Number of consecutive failures so far; should only be touched by
  826. * circuit_launch_new and circuit_*_failure_count.
  827. */
  828. static int n_circuit_failures = 0;
  829. /** Before the last time we called circuit_reset_failure_count(), were
  830. * there a lot of failures? */
  831. static int did_circs_fail_last_period = 0;
  832. /** Don't retry launching a new circuit if we try this many times with no
  833. * success. */
  834. #define MAX_CIRCUIT_FAILURES 5
  835. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  836. * details on arguments. */
  837. origin_circuit_t *
  838. circuit_launch_by_router(uint8_t purpose,
  839. routerinfo_t *exit, int flags)
  840. {
  841. origin_circuit_t *circ;
  842. extend_info_t *info = NULL;
  843. if (exit)
  844. info = extend_info_from_router(exit);
  845. circ = circuit_launch_by_extend_info(purpose, info, flags);
  846. if (info)
  847. extend_info_free(info);
  848. return circ;
  849. }
  850. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  851. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  852. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  853. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  854. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  855. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  856. * Return the newly allocated circuit on success, or NULL on failure. */
  857. origin_circuit_t *
  858. circuit_launch_by_extend_info(uint8_t purpose,
  859. extend_info_t *extend_info,
  860. int flags)
  861. {
  862. origin_circuit_t *circ;
  863. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  864. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  865. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  866. "circuit launch.");
  867. return NULL;
  868. }
  869. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  870. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  871. /* see if there are appropriate circs available to cannibalize. */
  872. /* XXX if we're planning to add a hop, perhaps we want to look for
  873. * internal circs rather than exit circs? -RD */
  874. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  875. if (circ) {
  876. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
  877. build_state_get_exit_nickname(circ->build_state), purpose);
  878. circ->_base.purpose = purpose;
  879. /* reset the birth date of this circ, else expire_building
  880. * will see it and think it's been trying to build since it
  881. * began. */
  882. circ->_base.timestamp_created = time(NULL);
  883. switch (purpose) {
  884. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  885. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  886. /* it's ready right now */
  887. break;
  888. case CIRCUIT_PURPOSE_C_INTRODUCING:
  889. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  890. case CIRCUIT_PURPOSE_C_GENERAL:
  891. /* need to add a new hop */
  892. tor_assert(extend_info);
  893. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  894. return NULL;
  895. break;
  896. default:
  897. log_warn(LD_BUG,
  898. "unexpected purpose %d when cannibalizing a circ.",
  899. purpose);
  900. tor_fragile_assert();
  901. return NULL;
  902. }
  903. return circ;
  904. }
  905. }
  906. if (did_circs_fail_last_period &&
  907. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  908. /* too many failed circs in a row. don't try. */
  909. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  910. return NULL;
  911. }
  912. /* try a circ. if it fails, circuit_mark_for_close will increment
  913. * n_circuit_failures */
  914. return circuit_establish_circuit(purpose, extend_info, flags);
  915. }
  916. /** Record another failure at opening a general circuit. When we have
  917. * too many, we'll stop trying for the remainder of this minute.
  918. */
  919. static void
  920. circuit_increment_failure_count(void)
  921. {
  922. ++n_circuit_failures;
  923. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  924. }
  925. /** Reset the failure count for opening general circuits. This means
  926. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  927. * stopping again.
  928. */
  929. void
  930. circuit_reset_failure_count(int timeout)
  931. {
  932. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  933. did_circs_fail_last_period = 1;
  934. else
  935. did_circs_fail_last_period = 0;
  936. n_circuit_failures = 0;
  937. }
  938. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  939. * there isn't one, and there isn't one on the way, launch one and return
  940. * 0. If it will never work, return -1.
  941. *
  942. * Write the found or in-progress or launched circ into *circp.
  943. */
  944. static int
  945. circuit_get_open_circ_or_launch(edge_connection_t *conn,
  946. uint8_t desired_circuit_purpose,
  947. origin_circuit_t **circp)
  948. {
  949. origin_circuit_t *circ;
  950. int check_exit_policy;
  951. int need_uptime, need_internal;
  952. int want_onehop;
  953. or_options_t *options = get_options();
  954. tor_assert(conn);
  955. tor_assert(circp);
  956. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  957. check_exit_policy =
  958. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  959. !conn->use_begindir &&
  960. !connection_edge_is_rendezvous_stream(conn);
  961. want_onehop = conn->want_onehop;
  962. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  963. smartlist_string_num_isin(options->LongLivedPorts,
  964. conn->socks_request->port);
  965. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  966. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  967. need_uptime, need_internal);
  968. if (circ) {
  969. *circp = circ;
  970. return 1; /* we're happy */
  971. }
  972. if (!want_onehop && !router_have_minimum_dir_info()) {
  973. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  974. int severity = LOG_NOTICE;
  975. /* FFFF if this is a tunneled directory fetch, don't yell
  976. * as loudly. the user doesn't even know it's happening. */
  977. if (options->UseBridges && bridges_known_but_down()) {
  978. log_fn(severity, LD_APP|LD_DIR,
  979. "Application request when we're believed to be "
  980. "offline. Optimistically trying known bridges again.");
  981. bridges_retry_all();
  982. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  983. log_fn(severity, LD_APP|LD_DIR,
  984. "Application request when we're believed to be "
  985. "offline. Optimistically trying directory fetches again.");
  986. routerlist_retry_directory_downloads(time(NULL));
  987. }
  988. }
  989. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  990. * 1, or when all directory attempts fail and directory_all_unreachable()
  991. * kills it.
  992. */
  993. return 0;
  994. }
  995. /* Do we need to check exit policy? */
  996. if (check_exit_policy) {
  997. if (!conn->chosen_exit_name) {
  998. struct in_addr in;
  999. uint32_t addr = 0;
  1000. if (tor_inet_aton(conn->socks_request->address, &in))
  1001. addr = ntohl(in.s_addr);
  1002. if (router_exit_policy_all_routers_reject(addr,
  1003. conn->socks_request->port,
  1004. need_uptime)) {
  1005. log_notice(LD_APP,
  1006. "No Tor server allows exit to %s:%d. Rejecting.",
  1007. safe_str(conn->socks_request->address),
  1008. conn->socks_request->port);
  1009. return -1;
  1010. }
  1011. } else {
  1012. /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
  1013. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1014. int opt = conn->chosen_exit_optional;
  1015. if (router && !connection_ap_can_use_exit(conn, router)) {
  1016. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1017. "Requested exit point '%s' would refuse request. %s.",
  1018. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1019. if (opt) {
  1020. conn->chosen_exit_optional = 0;
  1021. tor_free(conn->chosen_exit_name);
  1022. /* Try again. */
  1023. return circuit_get_open_circ_or_launch(conn,
  1024. desired_circuit_purpose,
  1025. circp);
  1026. }
  1027. return -1;
  1028. }
  1029. }
  1030. }
  1031. /* is one already on the way? */
  1032. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1033. need_uptime, need_internal);
  1034. if (circ)
  1035. log_debug(LD_CIRC, "one on the way!");
  1036. if (!circ) {
  1037. extend_info_t *extend_info=NULL;
  1038. uint8_t new_circ_purpose;
  1039. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1040. /* need to pick an intro point */
  1041. tor_assert(conn->rend_data);
  1042. extend_info = rend_client_get_random_intro(conn->rend_data);
  1043. if (!extend_info) {
  1044. log_info(LD_REND,
  1045. "No intro points for '%s': re-fetching service descriptor.",
  1046. safe_str(conn->rend_data->onion_address));
  1047. rend_client_refetch_v2_renddesc(conn->rend_data);
  1048. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1049. return 0;
  1050. }
  1051. log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
  1052. extend_info->nickname,
  1053. safe_str(conn->rend_data->onion_address));
  1054. }
  1055. /* If we have specified a particular exit node for our
  1056. * connection, then be sure to open a circuit to that exit node.
  1057. */
  1058. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1059. if (conn->chosen_exit_name) {
  1060. routerinfo_t *r;
  1061. int opt = conn->chosen_exit_optional;
  1062. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1063. if (r) {
  1064. extend_info = extend_info_from_router(r);
  1065. } else {
  1066. log_debug(LD_DIR, "considering %d, %s",
  1067. want_onehop, conn->chosen_exit_name);
  1068. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1069. /* We're asking for a one-hop circuit to a router that
  1070. * we don't have a routerinfo about. Make up an extend_info. */
  1071. char digest[DIGEST_LEN];
  1072. char *hexdigest = conn->chosen_exit_name+1;
  1073. tor_addr_t addr;
  1074. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1075. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1076. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1077. return -1;
  1078. }
  1079. if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
  1080. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1081. escaped_safe_str(conn->socks_request->address));
  1082. return -1;
  1083. }
  1084. extend_info = extend_info_alloc(conn->chosen_exit_name+1,
  1085. digest, NULL, &addr,
  1086. conn->socks_request->port);
  1087. } else {
  1088. /* We will need an onion key for the router, and we
  1089. * don't have one. Refuse or relax requirements. */
  1090. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1091. "Requested exit point '%s' is not known. %s.",
  1092. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1093. if (opt) {
  1094. conn->chosen_exit_optional = 0;
  1095. tor_free(conn->chosen_exit_name);
  1096. /* Try again with no requested exit */
  1097. return circuit_get_open_circ_or_launch(conn,
  1098. desired_circuit_purpose,
  1099. circp);
  1100. }
  1101. return -1;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1107. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1108. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1109. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1110. else
  1111. new_circ_purpose = desired_circuit_purpose;
  1112. {
  1113. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1114. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1115. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1116. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1117. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1118. flags);
  1119. }
  1120. if (extend_info)
  1121. extend_info_free(extend_info);
  1122. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  1123. /* help predict this next time */
  1124. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1125. if (circ) {
  1126. /* write the service_id into circ */
  1127. circ->rend_data = rend_data_dup(conn->rend_data);
  1128. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1129. circ->_base.state == CIRCUIT_STATE_OPEN)
  1130. rend_client_rendcirc_has_opened(circ);
  1131. }
  1132. }
  1133. }
  1134. if (!circ)
  1135. log_info(LD_APP,
  1136. "No safe circuit (purpose %d) ready for edge "
  1137. "connection; delaying.",
  1138. desired_circuit_purpose);
  1139. *circp = circ;
  1140. return 0;
  1141. }
  1142. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1143. * <b>circ</b>. */
  1144. static int
  1145. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1146. {
  1147. crypt_path_t *cpath, *cpath_next = NULL;
  1148. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1149. cpath_next = cpath->next;
  1150. if (crypt_path == cpath)
  1151. return 1;
  1152. }
  1153. return 0;
  1154. }
  1155. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1156. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1157. * hop in circ's cpath if <b>cpath</b> is NULL.
  1158. */
  1159. static void
  1160. link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
  1161. crypt_path_t *cpath)
  1162. {
  1163. /* add it into the linked list of streams on this circuit */
  1164. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1165. circ->_base.n_circ_id);
  1166. /* reset it, so we can measure circ timeouts */
  1167. apconn->_base.timestamp_lastread = time(NULL);
  1168. apconn->next_stream = circ->p_streams;
  1169. apconn->on_circuit = TO_CIRCUIT(circ);
  1170. /* assert_connection_ok(conn, time(NULL)); */
  1171. circ->p_streams = apconn;
  1172. if (cpath) { /* we were given one; use it */
  1173. tor_assert(cpath_is_on_circuit(circ, cpath));
  1174. apconn->cpath_layer = cpath;
  1175. } else { /* use the last hop in the circuit */
  1176. tor_assert(circ->cpath);
  1177. tor_assert(circ->cpath->prev);
  1178. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1179. apconn->cpath_layer = circ->cpath->prev;
  1180. }
  1181. }
  1182. /** If an exit wasn't specifically chosen, save the history for future
  1183. * use. */
  1184. static void
  1185. consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
  1186. {
  1187. int found_needle = 0;
  1188. or_options_t *options = get_options();
  1189. size_t len;
  1190. char *new_address;
  1191. char fp[HEX_DIGEST_LEN+1];
  1192. /* Search the addressmap for this conn's destination. */
  1193. /* If he's not in the address map.. */
  1194. if (!options->TrackHostExits ||
  1195. addressmap_have_mapping(conn->socks_request->address,
  1196. options->TrackHostExitsExpire))
  1197. return; /* nothing to track, or already mapped */
  1198. SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
  1199. if (cp[0] == '.') { /* match end */
  1200. if (cp[1] == '\0' ||
  1201. !strcasecmpend(conn->socks_request->address, cp) ||
  1202. !strcasecmp(conn->socks_request->address, &cp[1]))
  1203. found_needle = 1;
  1204. } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
  1205. found_needle = 1;
  1206. }
  1207. });
  1208. if (!found_needle || !circ->build_state->chosen_exit)
  1209. return;
  1210. /* write down the fingerprint of the chosen exit, not the nickname,
  1211. * because the chosen exit might not be named. */
  1212. base16_encode(fp, sizeof(fp),
  1213. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1214. /* Add this exit/hostname pair to the addressmap. */
  1215. len = strlen(conn->socks_request->address) + 1 /* '.' */ +
  1216. strlen(fp) + 1 /* '.' */ +
  1217. strlen("exit") + 1 /* '\0' */;
  1218. new_address = tor_malloc(len);
  1219. tor_snprintf(new_address, len, "%s.%s.exit",
  1220. conn->socks_request->address, fp);
  1221. addressmap_register(conn->socks_request->address, new_address,
  1222. time(NULL) + options->TrackHostExitsExpire,
  1223. ADDRMAPSRC_TRACKEXIT);
  1224. }
  1225. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1226. * begin or resolve cell as appropriate. Return values are as for
  1227. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1228. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1229. * <b>cpath</b> is NULL. */
  1230. int
  1231. connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  1232. origin_circuit_t *circ,
  1233. crypt_path_t *cpath)
  1234. {
  1235. tor_assert(conn);
  1236. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1237. conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
  1238. tor_assert(conn->socks_request);
  1239. tor_assert(circ);
  1240. tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
  1241. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1242. if (!circ->_base.timestamp_dirty)
  1243. circ->_base.timestamp_dirty = time(NULL);
  1244. link_apconn_to_circ(conn, circ, cpath);
  1245. tor_assert(conn->socks_request);
  1246. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1247. if (!conn->use_begindir)
  1248. consider_recording_trackhost(conn, circ);
  1249. if (connection_ap_handshake_send_begin(conn) < 0)
  1250. return -1;
  1251. } else {
  1252. if (connection_ap_handshake_send_resolve(conn) < 0)
  1253. return -1;
  1254. }
  1255. return 1;
  1256. }
  1257. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1258. * we don't find one: if conn cannot be handled by any known nodes,
  1259. * warn and return -1 (conn needs to die, and is maybe already marked);
  1260. * else launch new circuit (if necessary) and return 0.
  1261. * Otherwise, associate conn with a safe live circuit, do the
  1262. * right next step, and return 1.
  1263. */
  1264. /* XXXX this function should mark for close whenever it returns -1;
  1265. * its callers shouldn't have to worry about that. */
  1266. int
  1267. connection_ap_handshake_attach_circuit(edge_connection_t *conn)
  1268. {
  1269. int retval;
  1270. int conn_age;
  1271. int want_onehop;
  1272. tor_assert(conn);
  1273. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1274. tor_assert(conn->socks_request);
  1275. want_onehop = conn->want_onehop;
  1276. conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
  1277. if (conn_age >= get_options()->SocksTimeout) {
  1278. int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
  1279. LOG_INFO : LOG_NOTICE;
  1280. log_fn(severity, LD_APP,
  1281. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1282. conn_age, safe_str(conn->socks_request->address),
  1283. conn->socks_request->port);
  1284. return -1;
  1285. }
  1286. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1287. origin_circuit_t *circ=NULL;
  1288. if (conn->chosen_exit_name) {
  1289. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1290. int opt = conn->chosen_exit_optional;
  1291. if (!router && !want_onehop) {
  1292. /* We ran into this warning when trying to extend a circuit to a
  1293. * hidden service directory for which we didn't have a router
  1294. * descriptor. See flyspray task 767 for more details. We should
  1295. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1296. * directory requests as well. -KL*/
  1297. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1298. "Requested exit point '%s' is not known. %s.",
  1299. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1300. if (opt) {
  1301. conn->chosen_exit_optional = 0;
  1302. tor_free(conn->chosen_exit_name);
  1303. return 0;
  1304. }
  1305. return -1;
  1306. }
  1307. if (router && !connection_ap_can_use_exit(conn, router)) {
  1308. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1309. "Requested exit point '%s' would refuse request. %s.",
  1310. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1311. if (opt) {
  1312. conn->chosen_exit_optional = 0;
  1313. tor_free(conn->chosen_exit_name);
  1314. return 0;
  1315. }
  1316. return -1;
  1317. }
  1318. }
  1319. /* find the circuit that we should use, if there is one. */
  1320. retval = circuit_get_open_circ_or_launch(
  1321. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1322. if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
  1323. return retval;
  1324. log_debug(LD_APP|LD_CIRC,
  1325. "Attaching apconn to circ %d (stream %d sec old).",
  1326. circ->_base.n_circ_id, conn_age);
  1327. /* print the circ's path, so people can figure out which circs are
  1328. * sucking. */
  1329. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1330. /* We have found a suitable circuit for our conn. Hurray. */
  1331. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1332. } else { /* we're a rendezvous conn */
  1333. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1334. tor_assert(!conn->cpath_layer);
  1335. /* start by finding a rendezvous circuit for us */
  1336. retval = circuit_get_open_circ_or_launch(
  1337. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1338. if (retval < 0) return -1; /* failed */
  1339. if (retval > 0) {
  1340. tor_assert(rendcirc);
  1341. /* one is already established, attach */
  1342. log_info(LD_REND,
  1343. "rend joined circ %d already here. attaching. "
  1344. "(stream %d sec old)",
  1345. rendcirc->_base.n_circ_id, conn_age);
  1346. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1347. * them, since the process of rebuilding a rendezvous circ is so
  1348. * expensive. There is a tradeoff between linkability and
  1349. * feasibility, at this point.
  1350. */
  1351. rendcirc->_base.timestamp_dirty = time(NULL);
  1352. link_apconn_to_circ(conn, rendcirc, NULL);
  1353. if (connection_ap_handshake_send_begin(conn) < 0)
  1354. return 0; /* already marked, let them fade away */
  1355. return 1;
  1356. }
  1357. if (rendcirc && (rendcirc->_base.purpose ==
  1358. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1359. log_info(LD_REND,
  1360. "pending-join circ %d already here, with intro ack. "
  1361. "Stalling. (stream %d sec old)",
  1362. rendcirc->_base.n_circ_id, conn_age);
  1363. return 0;
  1364. }
  1365. /* it's on its way. find an intro circ. */
  1366. retval = circuit_get_open_circ_or_launch(
  1367. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1368. if (retval < 0) return -1; /* failed */
  1369. if (retval > 0) {
  1370. /* one has already sent the intro. keep waiting. */
  1371. circuit_t *c = NULL;
  1372. tor_assert(introcirc);
  1373. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1374. "Stalling. (stream %d sec old)",
  1375. introcirc->_base.n_circ_id,
  1376. rendcirc ? rendcirc->_base.n_circ_id : 0,
  1377. conn_age);
  1378. /* abort parallel intro circs, if any */
  1379. for (c = global_circuitlist; c; c = c->next) {
  1380. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1381. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1382. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1383. if (oc->rend_data &&
  1384. !rend_cmp_service_ids(conn->rend_data->onion_address,
  1385. oc->rend_data->onion_address)) {
  1386. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1387. "built in parallel.");
  1388. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1389. }
  1390. }
  1391. }
  1392. return 0;
  1393. }
  1394. /* now rendcirc and introcirc are each either undefined or not finished */
  1395. if (rendcirc && introcirc &&
  1396. rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1397. log_info(LD_REND,
  1398. "ready rend circ %d already here (no intro-ack yet on "
  1399. "intro %d). (stream %d sec old)",
  1400. rendcirc->_base.n_circ_id,
  1401. introcirc->_base.n_circ_id, conn_age);
  1402. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1403. if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
  1404. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1405. "introduction. (stream %d sec old)",
  1406. introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
  1407. conn_age);
  1408. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  1409. return -1;
  1410. }
  1411. rendcirc->_base.timestamp_dirty = time(NULL);
  1412. introcirc->_base.timestamp_dirty = time(NULL);
  1413. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1414. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1415. return 0;
  1416. }
  1417. }
  1418. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1419. "Stalling conn. (%d sec old)",
  1420. introcirc ? introcirc->_base.n_circ_id : 0,
  1421. rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
  1422. return 0;
  1423. }
  1424. }