circuituse.c 62 KB

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