circuituse.c 65 KB

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