circuituse.c 64 KB

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