circuituse.c 61 KB

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