circuituse.c 68 KB

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