circuituse.c 65 KB

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