circuituse.c 64 KB

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