circuituse.c 61 KB

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