circuituse.c 61 KB

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