circuituse.c 65 KB

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