circuituse.c 61 KB

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