circuituse.c 63 KB

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