circuituse.c 63 KB

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