circuituse.c 64 KB

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