circuituse.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831
  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-2017, 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 the right streams to
  9. * them.
  10. *
  11. * As distinct from circuitlist.c, which manages lookups to find circuits, and
  12. * circuitbuild.c, which handles the logistics of circuit construction, this
  13. * module keeps track of which streams can be attached to which circuits (in
  14. * circuit_get_best()), and attaches streams to circuits (with
  15. * circuit_try_attaching_streams(), connection_ap_handshake_attach_circuit(),
  16. * and connection_ap_handshake_attach_chosen_circuit() ).
  17. *
  18. * This module also makes sure that we are building circuits for all of the
  19. * predicted ports, using circuit_remove_handled_ports(),
  20. * circuit_stream_is_being_handled(), and circuit_build_needed_cirs(). It
  21. * handles launching circuits for specific targets using
  22. * circuit_launch_by_extend_info().
  23. *
  24. * This is also where we handle expiring circuits that have been around for
  25. * too long without actually completing, along with the circuit_build_timeout
  26. * logic in circuitstats.c.
  27. **/
  28. #include "or.h"
  29. #include "addressmap.h"
  30. #include "bridges.h"
  31. #include "channel.h"
  32. #include "circpathbias.h"
  33. #include "circuitbuild.h"
  34. #include "circuitlist.h"
  35. #include "circuitstats.h"
  36. #include "circuituse.h"
  37. #include "config.h"
  38. #include "connection.h"
  39. #include "connection_edge.h"
  40. #include "control.h"
  41. #include "entrynodes.h"
  42. #include "hs_common.h"
  43. #include "hs_client.h"
  44. #include "hs_circuit.h"
  45. #include "hs_ident.h"
  46. #include "nodelist.h"
  47. #include "networkstatus.h"
  48. #include "policies.h"
  49. #include "rendclient.h"
  50. #include "rendcommon.h"
  51. #include "rendservice.h"
  52. #include "rephist.h"
  53. #include "router.h"
  54. #include "routerlist.h"
  55. static void circuit_expire_old_circuits_clientside(void);
  56. static void circuit_increment_failure_count(void);
  57. /** Check whether the hidden service destination of the stream at
  58. * <b>edge_conn</b> is the same as the destination of the circuit at
  59. * <b>origin_circ</b>. */
  60. static int
  61. circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
  62. const origin_circuit_t *origin_circ)
  63. {
  64. /* Check if this is a v2 rendezvous circ/stream */
  65. if ((edge_conn->rend_data && !origin_circ->rend_data) ||
  66. (!edge_conn->rend_data && origin_circ->rend_data) ||
  67. (edge_conn->rend_data && origin_circ->rend_data &&
  68. rend_cmp_service_ids(rend_data_get_address(edge_conn->rend_data),
  69. rend_data_get_address(origin_circ->rend_data)))) {
  70. /* this circ is not for this conn */
  71. return 0;
  72. }
  73. /* Check if this is a v3 rendezvous circ/stream */
  74. if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
  75. (!edge_conn->hs_ident && origin_circ->hs_ident) ||
  76. (edge_conn->hs_ident && origin_circ->hs_ident &&
  77. !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
  78. &origin_circ->hs_ident->identity_pk))) {
  79. /* this circ is not for this conn */
  80. return 0;
  81. }
  82. return 1;
  83. }
  84. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  85. * Else return 0.
  86. */
  87. static int
  88. circuit_is_acceptable(const origin_circuit_t *origin_circ,
  89. const entry_connection_t *conn,
  90. int must_be_open, uint8_t purpose,
  91. int need_uptime, int need_internal,
  92. time_t now)
  93. {
  94. const circuit_t *circ = TO_CIRCUIT(origin_circ);
  95. const node_t *exitnode;
  96. cpath_build_state_t *build_state;
  97. tor_assert(circ);
  98. tor_assert(conn);
  99. tor_assert(conn->socks_request);
  100. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
  101. return 0; /* ignore non-open circs */
  102. if (circ->marked_for_close)
  103. return 0;
  104. /* if this circ isn't our purpose, skip. */
  105. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  106. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  107. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  108. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  109. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  110. return 0;
  111. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  112. !must_be_open) {
  113. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  114. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  115. return 0;
  116. } else {
  117. if (purpose != circ->purpose)
  118. return 0;
  119. }
  120. /* If this is a timed-out hidden service circuit, skip it. */
  121. if (origin_circ->hs_circ_has_timed_out) {
  122. return 0;
  123. }
  124. if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  125. purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  126. if (circ->timestamp_dirty &&
  127. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  128. return 0;
  129. }
  130. if (origin_circ->unusable_for_new_conns)
  131. return 0;
  132. /* decide if this circ is suitable for this conn */
  133. /* for rend circs, circ->cpath->prev is not the last router in the
  134. * circuit, it's the magical extra service hop. so just check the nickname
  135. * of the one we meant to finish at.
  136. */
  137. build_state = origin_circ->build_state;
  138. exitnode = build_state_get_exit_node(build_state);
  139. if (need_uptime && !build_state->need_uptime)
  140. return 0;
  141. if (need_internal != build_state->is_internal)
  142. return 0;
  143. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  144. tor_addr_t addr;
  145. const int family = tor_addr_parse(&addr, conn->socks_request->address);
  146. if (!exitnode && !build_state->onehop_tunnel) {
  147. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  148. return 0; /* this circuit is screwed and doesn't know it yet,
  149. * or is a rendezvous circuit. */
  150. }
  151. if (build_state->onehop_tunnel) {
  152. if (!conn->want_onehop) {
  153. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  154. return 0;
  155. }
  156. tor_assert(conn->chosen_exit_name);
  157. if (build_state->chosen_exit) {
  158. char digest[DIGEST_LEN];
  159. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  160. return 0; /* broken digest, we don't want it */
  161. if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
  162. DIGEST_LEN))
  163. return 0; /* this is a circuit to somewhere else */
  164. if (tor_digest_is_zero(digest)) {
  165. /* we don't know the digest; have to compare addr:port */
  166. if (family < 0 ||
  167. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  168. build_state->chosen_exit->port != conn->socks_request->port)
  169. return 0;
  170. }
  171. }
  172. } else {
  173. if (conn->want_onehop) {
  174. /* don't use three-hop circuits -- that could hurt our anonymity. */
  175. return 0;
  176. }
  177. }
  178. if (origin_circ->prepend_policy && family != -1) {
  179. int r = compare_tor_addr_to_addr_policy(&addr,
  180. conn->socks_request->port,
  181. origin_circ->prepend_policy);
  182. if (r == ADDR_POLICY_REJECTED)
  183. return 0;
  184. }
  185. if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
  186. /* can't exit from this router */
  187. return 0;
  188. }
  189. } else { /* not general: this might be a rend circuit */
  190. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  191. if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
  192. return 0;
  193. }
  194. }
  195. if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
  196. /* conn needs to be isolated from other conns that have already used
  197. * origin_circ */
  198. return 0;
  199. }
  200. return 1;
  201. }
  202. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  203. * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
  204. */
  205. static int
  206. circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
  207. const entry_connection_t *conn)
  208. {
  209. const circuit_t *a = TO_CIRCUIT(oa);
  210. const circuit_t *b = TO_CIRCUIT(ob);
  211. const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
  212. int a_bits, b_bits;
  213. /* If one of the circuits was allowed to live due to relaxing its timeout,
  214. * it is definitely worse (it's probably a much slower path). */
  215. if (oa->relaxed_timeout && !ob->relaxed_timeout)
  216. return 0; /* ob is better. It's not relaxed. */
  217. if (!oa->relaxed_timeout && ob->relaxed_timeout)
  218. return 1; /* oa is better. It's not relaxed. */
  219. switch (purpose) {
  220. case CIRCUIT_PURPOSE_C_GENERAL:
  221. /* if it's used but less dirty it's best;
  222. * else if it's more recently created it's best
  223. */
  224. if (b->timestamp_dirty) {
  225. if (a->timestamp_dirty &&
  226. a->timestamp_dirty > b->timestamp_dirty)
  227. return 1;
  228. } else {
  229. if (a->timestamp_dirty ||
  230. timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
  231. return 1;
  232. if (ob->build_state->is_internal)
  233. /* XXXX++ what the heck is this internal thing doing here. I
  234. * think we can get rid of it. circuit_is_acceptable() already
  235. * makes sure that is_internal is exactly what we need it to
  236. * be. -RD */
  237. return 1;
  238. }
  239. break;
  240. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  241. /* the closer it is to ack_wait the better it is */
  242. if (a->purpose > b->purpose)
  243. return 1;
  244. break;
  245. case CIRCUIT_PURPOSE_C_REND_JOINED:
  246. /* the closer it is to rend_joined the better it is */
  247. if (a->purpose > b->purpose)
  248. return 1;
  249. break;
  250. }
  251. /* XXXX Maybe this check should get a higher priority to avoid
  252. * using up circuits too rapidly. */
  253. a_bits = connection_edge_update_circuit_isolation(conn,
  254. (origin_circuit_t*)oa, 1);
  255. b_bits = connection_edge_update_circuit_isolation(conn,
  256. (origin_circuit_t*)ob, 1);
  257. /* if x_bits < 0, then we have not used x for anything; better not to dirty
  258. * a connection if we can help it. */
  259. if (a_bits < 0) {
  260. return 0;
  261. } else if (b_bits < 0) {
  262. return 1;
  263. }
  264. a_bits &= ~ oa->isolation_flags_mixed;
  265. a_bits &= ~ ob->isolation_flags_mixed;
  266. if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
  267. /* The fewer new restrictions we need to make on a circuit for stream
  268. * isolation, the better. */
  269. return 1;
  270. }
  271. return 0;
  272. }
  273. /** Find the best circ that conn can use, preferably one which is
  274. * dirty. Circ must not be too old.
  275. *
  276. * Conn must be defined.
  277. *
  278. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  279. *
  280. * circ_purpose specifies what sort of circuit we must have.
  281. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  282. *
  283. * If it's REND_JOINED and must_be_open==0, then return the closest
  284. * rendezvous-purposed circuit that you can find.
  285. *
  286. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  287. * closest introduce-purposed circuit that you can find.
  288. */
  289. static origin_circuit_t *
  290. circuit_get_best(const entry_connection_t *conn,
  291. int must_be_open, uint8_t purpose,
  292. int need_uptime, int need_internal)
  293. {
  294. origin_circuit_t *best=NULL;
  295. struct timeval now;
  296. int intro_going_on_but_too_old = 0;
  297. tor_assert(conn);
  298. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  299. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  300. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  301. tor_gettimeofday(&now);
  302. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  303. origin_circuit_t *origin_circ;
  304. if (!CIRCUIT_IS_ORIGIN(circ))
  305. continue;
  306. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  307. /* Log an info message if we're going to launch a new intro circ in
  308. * parallel */
  309. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  310. !must_be_open && origin_circ->hs_circ_has_timed_out) {
  311. intro_going_on_but_too_old = 1;
  312. continue;
  313. }
  314. if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
  315. need_uptime,need_internal, (time_t)now.tv_sec))
  316. continue;
  317. /* now this is an acceptable circ to hand back. but that doesn't
  318. * mean it's the *best* circ to hand back. try to decide.
  319. */
  320. if (!best || circuit_is_better(origin_circ,best,conn))
  321. best = origin_circ;
  322. }
  323. SMARTLIST_FOREACH_END(circ);
  324. if (!best && intro_going_on_but_too_old)
  325. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  326. "right now, but it has already taken quite a while. Starting "
  327. "one in parallel.");
  328. return best;
  329. }
  330. /** Return the number of not-yet-open general-purpose origin circuits. */
  331. static int
  332. count_pending_general_client_circuits(void)
  333. {
  334. int count = 0;
  335. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  336. if (circ->marked_for_close ||
  337. circ->state == CIRCUIT_STATE_OPEN ||
  338. circ->purpose != CIRCUIT_PURPOSE_C_GENERAL ||
  339. !CIRCUIT_IS_ORIGIN(circ))
  340. continue;
  341. ++count;
  342. }
  343. SMARTLIST_FOREACH_END(circ);
  344. return count;
  345. }
  346. #if 0
  347. /** Check whether, according to the policies in <b>options</b>, the
  348. * circuit <b>circ</b> makes sense. */
  349. /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
  350. * Also, it doesn't have the right definition of an exit circuit. Also,
  351. * it's never called. */
  352. int
  353. circuit_conforms_to_options(const origin_circuit_t *circ,
  354. const or_options_t *options)
  355. {
  356. const crypt_path_t *cpath, *cpath_next = NULL;
  357. /* first check if it includes any excluded nodes */
  358. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  359. cpath_next = cpath->next;
  360. if (routerset_contains_extendinfo(options->ExcludeNodes,
  361. cpath->extend_info))
  362. return 0;
  363. }
  364. /* then consider the final hop */
  365. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  366. circ->cpath->prev->extend_info))
  367. return 0;
  368. return 1;
  369. }
  370. #endif
  371. /** Close all circuits that start at us, aren't open, and were born
  372. * at least CircuitBuildTimeout seconds ago.
  373. */
  374. void
  375. circuit_expire_building(void)
  376. {
  377. /* circ_times.timeout_ms and circ_times.close_ms are from
  378. * circuit_build_times_get_initial_timeout() if we haven't computed
  379. * custom timeouts yet */
  380. struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
  381. close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
  382. cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
  383. const or_options_t *options = get_options();
  384. struct timeval now;
  385. cpath_build_state_t *build_state;
  386. int any_opened_circs = 0;
  387. tor_gettimeofday(&now);
  388. /* Check to see if we have any opened circuits. If we don't,
  389. * we want to be more lenient with timeouts, in case the
  390. * user has relocated and/or changed network connections.
  391. * See bug #3443. */
  392. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, next_circ) {
  393. if (!CIRCUIT_IS_ORIGIN(next_circ) || /* didn't originate here */
  394. next_circ->marked_for_close) { /* don't mess with marked circs */
  395. continue;
  396. }
  397. if (TO_ORIGIN_CIRCUIT(next_circ)->has_opened &&
  398. next_circ->state == CIRCUIT_STATE_OPEN &&
  399. TO_ORIGIN_CIRCUIT(next_circ)->build_state &&
  400. TO_ORIGIN_CIRCUIT(next_circ)->build_state->desired_path_len
  401. == DEFAULT_ROUTE_LEN) {
  402. any_opened_circs = 1;
  403. break;
  404. }
  405. } SMARTLIST_FOREACH_END(next_circ);
  406. #define SET_CUTOFF(target, msec) do { \
  407. long ms = tor_lround(msec); \
  408. struct timeval diff; \
  409. diff.tv_sec = ms / 1000; \
  410. diff.tv_usec = (int)((ms % 1000) * 1000); \
  411. timersub(&now, &diff, &target); \
  412. } while (0)
  413. /**
  414. * Because circuit build timeout is calculated only based on 3 hop
  415. * general purpose circuit construction, we need to scale the timeout
  416. * to make it properly apply to longer circuits, and circuits of
  417. * certain usage types. The following diagram illustrates how we
  418. * derive the scaling below. In short, we calculate the number
  419. * of times our telescoping-based circuit construction causes cells
  420. * to traverse each link for the circuit purpose types in question,
  421. * and then assume each link is equivalent.
  422. *
  423. * OP --a--> A --b--> B --c--> C
  424. * OP --a--> A --b--> B --c--> C --d--> D
  425. *
  426. * Let h = a = b = c = d
  427. *
  428. * Three hops (general_cutoff)
  429. * RTTs = 3a + 2b + c
  430. * RTTs = 6h
  431. * Cannibalized:
  432. * RTTs = a+b+c+d
  433. * RTTs = 4h
  434. * Four hops:
  435. * RTTs = 4a + 3b + 2c + d
  436. * RTTs = 10h
  437. * Client INTRODUCE1+ACK: // XXX: correct?
  438. * RTTs = 5a + 4b + 3c + 2d
  439. * RTTs = 14h
  440. * Server intro:
  441. * RTTs = 4a + 3b + 2c
  442. * RTTs = 9h
  443. */
  444. SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
  445. SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
  446. /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
  447. * 4th hop. */
  448. SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
  449. /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
  450. * Use the stream cutoff (more or less). */
  451. SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
  452. /* Be lenient with cannibalized circs. They already survived the official
  453. * CBT, and they're usually not performance-critical. */
  454. SET_CUTOFF(cannibalized_cutoff,
  455. MAX(get_circuit_build_close_time_ms()*(4/6.0),
  456. options->CircuitStreamTimeout * 1000) + 1000);
  457. /* Intro circs have an extra round trip (and are also 4 hops long) */
  458. SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
  459. /* Server intro circs have an extra round trip */
  460. SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
  461. SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
  462. SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
  463. SET_CUTOFF(hs_extremely_old_cutoff,
  464. MAX(get_circuit_build_close_time_ms()*2 + 1000,
  465. options->SocksTimeout * 1000));
  466. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
  467. struct timeval cutoff;
  468. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  469. victim->marked_for_close) /* don't mess with marked circs */
  470. continue;
  471. /* If we haven't yet started the first hop, it means we don't have
  472. * any orconns available, and thus have not started counting time yet
  473. * for this circuit. See circuit_deliver_create_cell() and uses of
  474. * timestamp_began.
  475. *
  476. * Continue to wait in this case. The ORConn should timeout
  477. * independently and kill us then.
  478. */
  479. if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
  480. continue;
  481. }
  482. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  483. if (build_state && build_state->onehop_tunnel)
  484. cutoff = begindir_cutoff;
  485. else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  486. cutoff = close_cutoff;
  487. else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  488. victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  489. cutoff = c_intro_cutoff;
  490. else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  491. cutoff = s_intro_cutoff;
  492. else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  493. cutoff = stream_cutoff;
  494. else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
  495. cutoff = close_cutoff;
  496. else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
  497. victim->state != CIRCUIT_STATE_OPEN)
  498. cutoff = cannibalized_cutoff;
  499. else if (build_state && build_state->desired_path_len >= 4)
  500. cutoff = fourhop_cutoff;
  501. else
  502. cutoff = general_cutoff;
  503. if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
  504. cutoff = hs_extremely_old_cutoff;
  505. if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
  506. continue; /* it's still young, leave it alone */
  507. /* We need to double-check the opened state here because
  508. * we don't want to consider opened 1-hop dircon circuits for
  509. * deciding when to relax the timeout, but we *do* want to relax
  510. * those circuits too if nothing else is opened *and* they still
  511. * aren't either. */
  512. if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
  513. /* It's still young enough that we wouldn't close it, right? */
  514. if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
  515. if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
  516. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
  517. == CPATH_STATE_OPEN;
  518. log_info(LD_CIRC,
  519. "No circuits are opened. Relaxing timeout for circuit %d "
  520. "(a %s %d-hop circuit in state %s with channel state %s).",
  521. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  522. circuit_purpose_to_string(victim->purpose),
  523. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  524. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  525. -1,
  526. circuit_state_to_string(victim->state),
  527. channel_state_to_string(victim->n_chan->state));
  528. /* We count the timeout here for CBT, because technically this
  529. * was a timeout, and the timeout value needs to reset if we
  530. * see enough of them. Note this means we also need to avoid
  531. * double-counting below, too. */
  532. circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
  533. first_hop_succeeded);
  534. TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
  535. }
  536. continue;
  537. } else {
  538. static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
  539. const double build_close_ms = get_circuit_build_close_time_ms();
  540. log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
  541. "No circuits are opened. Relaxed timeout for circuit %d "
  542. "(a %s %d-hop circuit in state %s with channel state %s) to "
  543. "%ldms. However, it appears the circuit has timed out "
  544. "anyway.",
  545. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  546. circuit_purpose_to_string(victim->purpose),
  547. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  548. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  549. -1,
  550. circuit_state_to_string(victim->state),
  551. channel_state_to_string(victim->n_chan->state),
  552. (long)build_close_ms);
  553. }
  554. }
  555. #if 0
  556. /* some debug logs, to help track bugs */
  557. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  558. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  559. if (!victim->timestamp_dirty)
  560. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
  561. "(clean).",
  562. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  563. victim->purpose, victim->build_state->chosen_exit_name,
  564. victim->n_circ_id);
  565. else
  566. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
  567. "%d secs since dirty.",
  568. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  569. victim->purpose, victim->build_state->chosen_exit_name,
  570. victim->n_circ_id,
  571. (int)(now - victim->timestamp_dirty));
  572. }
  573. #endif
  574. /* if circ is !open, or if it's open but purpose is a non-finished
  575. * intro or rend, then mark it for close */
  576. if (victim->state == CIRCUIT_STATE_OPEN) {
  577. switch (victim->purpose) {
  578. default: /* most open circuits can be left alone. */
  579. continue; /* yes, continue inside a switch refers to the nearest
  580. * enclosing loop. C is smart. */
  581. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  582. break; /* too old, need to die */
  583. case CIRCUIT_PURPOSE_C_REND_READY:
  584. /* it's a rend_ready circ -- has it already picked a query? */
  585. /* c_rend_ready circs measure age since timestamp_dirty,
  586. * because that's set when they switch purposes
  587. */
  588. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  589. victim->timestamp_dirty > cutoff.tv_sec)
  590. continue;
  591. break;
  592. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  593. /* Open path bias testing circuits are given a long
  594. * time to complete the test, but not forever */
  595. TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
  596. break;
  597. case CIRCUIT_PURPOSE_C_INTRODUCING:
  598. /* We keep old introducing circuits around for
  599. * a while in parallel, and they can end up "opened".
  600. * We decide below if we're going to mark them timed
  601. * out and eventually close them.
  602. */
  603. break;
  604. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  605. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  606. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  607. /* rend and intro circs become dirty each time they
  608. * make an introduction attempt. so timestamp_dirty
  609. * will reflect the time since the last attempt.
  610. */
  611. if (victim->timestamp_dirty > cutoff.tv_sec)
  612. continue;
  613. break;
  614. }
  615. } else { /* circuit not open, consider recording failure as timeout */
  616. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
  617. TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
  618. if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
  619. log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
  620. "yet has attached streams!",
  621. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  622. victim->purpose,
  623. circuit_purpose_to_string(victim->purpose));
  624. tor_fragile_assert();
  625. continue;
  626. }
  627. if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
  628. circuit_build_times_enough_to_compute(get_circuit_build_times())) {
  629. /* Circuits are allowed to last longer for measurement.
  630. * Switch their purpose and wait. */
  631. if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  632. control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
  633. CIRC_EVENT_FAILED,
  634. END_CIRC_REASON_TIMEOUT);
  635. circuit_change_purpose(victim, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
  636. /* Record this failure to check for too many timeouts
  637. * in a row. This function does not record a time value yet
  638. * (we do that later); it only counts the fact that we did
  639. * have a timeout. We also want to avoid double-counting
  640. * already "relaxed" circuits, which are counted above. */
  641. if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
  642. circuit_build_times_count_timeout(
  643. get_circuit_build_times_mutable(),
  644. first_hop_succeeded);
  645. }
  646. continue;
  647. }
  648. /*
  649. * If the circuit build time is much greater than we would have cut
  650. * it off at, we probably had a suspend event along this codepath,
  651. * and we should discard the value.
  652. */
  653. if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
  654. log_notice(LD_CIRC,
  655. "Extremely large value for circuit build timeout: %lds. "
  656. "Assuming clock jump. Purpose %d (%s)",
  657. (long)(now.tv_sec - victim->timestamp_began.tv_sec),
  658. victim->purpose,
  659. circuit_purpose_to_string(victim->purpose));
  660. } else if (circuit_build_times_count_close(
  661. get_circuit_build_times_mutable(),
  662. first_hop_succeeded,
  663. (time_t)victim->timestamp_created.tv_sec)) {
  664. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  665. }
  666. }
  667. }
  668. /* If this is a hidden service client circuit which is far enough along in
  669. * connecting to its destination, and we haven't already flagged it as
  670. * 'timed out', flag it so we'll launch another intro or rend circ, but
  671. * don't mark it for close yet.
  672. *
  673. * (Circs flagged as 'timed out' are given a much longer timeout
  674. * period above, so we won't close them in the next call to
  675. * circuit_expire_building.) */
  676. if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
  677. switch (victim->purpose) {
  678. case CIRCUIT_PURPOSE_C_REND_READY:
  679. /* We only want to spare a rend circ if it has been specified in
  680. * an INTRODUCE1 cell sent to a hidden service. A circ's
  681. * pending_final_cpath field is non-NULL iff it is a rend circ
  682. * and we have tried to send an INTRODUCE1 cell specifying it.
  683. * Thus, if the pending_final_cpath field *is* NULL, then we
  684. * want to not spare it. */
  685. if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
  686. TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
  687. NULL)
  688. break;
  689. /* fallthrough! */
  690. case CIRCUIT_PURPOSE_C_INTRODUCING:
  691. /* connection_ap_handshake_attach_circuit() will relaunch for us */
  692. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  693. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  694. /* If we have reached this line, we want to spare the circ for now. */
  695. log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
  696. "as timed-out HS circ",
  697. (unsigned)victim->n_circ_id,
  698. victim->state, circuit_state_to_string(victim->state),
  699. victim->purpose);
  700. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  701. continue;
  702. default:
  703. break;
  704. }
  705. }
  706. /* If this is a service-side rendezvous circuit which is far
  707. * enough along in connecting to its destination, consider sparing
  708. * it. */
  709. if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
  710. victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  711. log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
  712. "as timed-out HS circ; relaunching rendezvous attempt.",
  713. (unsigned)victim->n_circ_id,
  714. victim->state, circuit_state_to_string(victim->state),
  715. victim->purpose);
  716. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  717. hs_circ_retry_service_rendezvous_point(TO_ORIGIN_CIRCUIT(victim));
  718. continue;
  719. }
  720. if (victim->n_chan)
  721. log_info(LD_CIRC,
  722. "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
  723. "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  724. channel_get_canonical_remote_descr(victim->n_chan),
  725. (unsigned)victim->n_circ_id,
  726. TO_ORIGIN_CIRCUIT(victim)->has_opened,
  727. victim->state, circuit_state_to_string(victim->state),
  728. victim->purpose,
  729. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  730. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  731. -1);
  732. else
  733. log_info(LD_CIRC,
  734. "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
  735. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  736. (unsigned)victim->n_circ_id,
  737. TO_ORIGIN_CIRCUIT(victim)->has_opened,
  738. victim->state,
  739. circuit_state_to_string(victim->state), victim->purpose,
  740. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  741. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  742. -1);
  743. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  744. if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  745. circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
  746. else
  747. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  748. pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
  749. } SMARTLIST_FOREACH_END(victim);
  750. }
  751. /**
  752. * Mark for close all circuits that start here, that were built through a
  753. * guard we weren't sure if we wanted to use, and that have been waiting
  754. * around for way too long.
  755. */
  756. void
  757. circuit_expire_waiting_for_better_guard(void)
  758. {
  759. SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
  760. origin_circuit_t *, circ) {
  761. if (TO_CIRCUIT(circ)->marked_for_close)
  762. continue;
  763. if (circ->guard_state == NULL)
  764. continue;
  765. if (entry_guard_state_should_expire(circ->guard_state))
  766. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
  767. } SMARTLIST_FOREACH_END(circ);
  768. }
  769. /** For debugging #8387: track when we last called
  770. * circuit_expire_old_circuits_clientside. */
  771. static time_t last_expired_clientside_circuits = 0;
  772. /**
  773. * As a diagnostic for bug 8387, log information about how many one-hop
  774. * circuits we have around that have been there for at least <b>age</b>
  775. * seconds. Log a few of them.
  776. * Ignores Single Onion Service intro and Tor2web redezvous circuits, they are
  777. * expected to be long-term one-hop circuits.
  778. */
  779. void
  780. circuit_log_ancient_one_hop_circuits(int age)
  781. {
  782. #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
  783. time_t now = time(NULL);
  784. time_t cutoff = now - age;
  785. int n_found = 0;
  786. smartlist_t *log_these = smartlist_new();
  787. const or_options_t *options = get_options();
  788. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  789. const origin_circuit_t *ocirc;
  790. if (! CIRCUIT_IS_ORIGIN(circ))
  791. continue;
  792. if (circ->timestamp_created.tv_sec >= cutoff)
  793. continue;
  794. /* Single Onion Services deliberately make long term one-hop intro
  795. * connections. We only ignore active intro point connections, if we take
  796. * a long time establishing, that's worth logging. */
  797. if (rend_service_allow_non_anonymous_connection(options) &&
  798. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)
  799. continue;
  800. /* Tor2web deliberately makes long term one-hop rend connections,
  801. * particularly when Tor2webRendezvousPoints is used. We only ignore
  802. * active rend point connections, if we take a long time to rendezvous,
  803. * that's worth logging. */
  804. if (rend_client_allow_non_anonymous_connection(options) &&
  805. circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  806. continue;
  807. ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
  808. if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
  809. ++n_found;
  810. if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
  811. smartlist_add(log_these, (origin_circuit_t*) ocirc);
  812. }
  813. }
  814. SMARTLIST_FOREACH_END(circ);
  815. if (n_found == 0)
  816. goto done;
  817. log_notice(LD_HEARTBEAT,
  818. "Diagnostic for issue 8387: Found %d one-hop circuits more "
  819. "than %d seconds old! Logging %d...",
  820. n_found, age, smartlist_len(log_these));
  821. SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
  822. char created[ISO_TIME_LEN+1];
  823. int stream_num;
  824. const edge_connection_t *conn;
  825. char *dirty = NULL;
  826. const circuit_t *circ = TO_CIRCUIT(ocirc);
  827. format_local_iso_time(created,
  828. (time_t)circ->timestamp_created.tv_sec);
  829. if (circ->timestamp_dirty) {
  830. char dirty_since[ISO_TIME_LEN+1];
  831. format_local_iso_time(dirty_since, circ->timestamp_dirty);
  832. tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
  833. dirty_since, (long)(now - circ->timestamp_dirty),
  834. (long) options->MaxCircuitDirtiness);
  835. } else {
  836. dirty = tor_strdup("Not marked dirty");
  837. }
  838. log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
  839. "Package window: %d. "
  840. "%s for new conns. %s.",
  841. ocirc_sl_idx,
  842. created,
  843. circuit_state_to_string(circ->state),
  844. circuit_purpose_to_string(circ->purpose),
  845. circ->marked_for_close ? "Marked" : "Not marked",
  846. circ->package_window,
  847. ocirc->unusable_for_new_conns ? "Not usable" : "usable",
  848. dirty);
  849. tor_free(dirty);
  850. stream_num = 0;
  851. for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
  852. const connection_t *c = TO_CONN(conn);
  853. char stream_created[ISO_TIME_LEN+1];
  854. if (++stream_num >= 5)
  855. break;
  856. format_local_iso_time(stream_created, c->timestamp_created);
  857. log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
  858. "%s conn in state %s. "
  859. "It is %slinked and %sreading from a linked connection %p. "
  860. "Package window %d. "
  861. "%s for close (%s:%d). Hold-open is %sset. "
  862. "Has %ssent RELAY_END. %s on circuit.",
  863. stream_num,
  864. stream_created,
  865. conn_type_to_string(c->type),
  866. conn_state_to_string(c->type, c->state),
  867. c->linked ? "" : "not ",
  868. c->reading_from_linked_conn ? "": "not",
  869. c->linked_conn,
  870. conn->package_window,
  871. c->marked_for_close ? "Marked" : "Not marked",
  872. c->marked_for_close_file ? c->marked_for_close_file : "--",
  873. c->marked_for_close,
  874. c->hold_open_until_flushed ? "" : "not ",
  875. conn->edge_has_sent_end ? "" : "not ",
  876. conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
  877. if (! c->linked_conn)
  878. continue;
  879. c = c->linked_conn;
  880. log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
  881. "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
  882. conn_type_to_string(c->type),
  883. conn_state_to_string(c->type, c->state),
  884. c->purpose,
  885. c->marked_for_close ? "Marked" : "Not marked",
  886. c->marked_for_close_file ? c->marked_for_close_file : "--",
  887. c->marked_for_close,
  888. c->hold_open_until_flushed ? "" : "not ");
  889. }
  890. } SMARTLIST_FOREACH_END(ocirc);
  891. log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
  892. "circuit_expire_old_circuits_clientside().",
  893. (long)(now - last_expired_clientside_circuits));
  894. done:
  895. smartlist_free(log_these);
  896. }
  897. /** Remove any elements in <b>needed_ports</b> that are handled by an
  898. * open or in-progress circuit.
  899. */
  900. void
  901. circuit_remove_handled_ports(smartlist_t *needed_ports)
  902. {
  903. int i;
  904. uint16_t *port;
  905. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  906. port = smartlist_get(needed_ports, i);
  907. tor_assert(*port);
  908. if (circuit_stream_is_being_handled(NULL, *port,
  909. MIN_CIRCUITS_HANDLING_STREAM)) {
  910. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  911. smartlist_del(needed_ports, i--);
  912. tor_free(port);
  913. } else {
  914. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  915. }
  916. }
  917. }
  918. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  919. * will have an acceptable exit node for exit stream <b>conn</b> if it
  920. * is defined, else for "*:port".
  921. * Else return 0.
  922. */
  923. int
  924. circuit_stream_is_being_handled(entry_connection_t *conn,
  925. uint16_t port, int min)
  926. {
  927. const node_t *exitnode;
  928. int num=0;
  929. time_t now = time(NULL);
  930. int need_uptime = smartlist_contains_int_as_string(
  931. get_options()->LongLivedPorts,
  932. conn ? conn->socks_request->port : port);
  933. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  934. if (CIRCUIT_IS_ORIGIN(circ) &&
  935. !circ->marked_for_close &&
  936. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  937. (!circ->timestamp_dirty ||
  938. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  939. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  940. cpath_build_state_t *build_state = origin_circ->build_state;
  941. if (build_state->is_internal || build_state->onehop_tunnel)
  942. continue;
  943. if (origin_circ->unusable_for_new_conns)
  944. continue;
  945. exitnode = build_state_get_exit_node(build_state);
  946. if (exitnode && (!need_uptime || build_state->need_uptime)) {
  947. int ok;
  948. if (conn) {
  949. ok = connection_ap_can_use_exit(conn, exitnode);
  950. } else {
  951. addr_policy_result_t r;
  952. r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
  953. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  954. }
  955. if (ok) {
  956. if (++num >= min)
  957. return 1;
  958. }
  959. }
  960. }
  961. }
  962. SMARTLIST_FOREACH_END(circ);
  963. return 0;
  964. }
  965. /** Don't keep more than this many unused open circuits around. */
  966. #define MAX_UNUSED_OPEN_CIRCUITS 14
  967. /* Return true if a circuit is available for use, meaning that it is open,
  968. * clean, usable for new multi-hop connections, and a general purpose origin
  969. * circuit.
  970. * Accept any kind of circuit, return false if the above conditions are not
  971. * met. */
  972. STATIC int
  973. circuit_is_available_for_use(const circuit_t *circ)
  974. {
  975. const origin_circuit_t *origin_circ;
  976. cpath_build_state_t *build_state;
  977. if (!CIRCUIT_IS_ORIGIN(circ))
  978. return 0; /* We first filter out only origin circuits before doing the
  979. following checks. */
  980. if (circ->marked_for_close)
  981. return 0; /* Don't mess with marked circs */
  982. if (circ->timestamp_dirty)
  983. return 0; /* Only count clean circs */
  984. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  985. return 0; /* We only pay attention to general purpose circuits.
  986. General purpose circuits are always origin circuits. */
  987. origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
  988. if (origin_circ->unusable_for_new_conns)
  989. return 0;
  990. build_state = origin_circ->build_state;
  991. if (build_state->onehop_tunnel)
  992. return 0;
  993. return 1;
  994. }
  995. /* Return true if we need any more exit circuits.
  996. * needs_uptime and needs_capacity are set only if we need more exit circuits.
  997. * Check if we know of a port that's been requested recently and no circuit
  998. * is currently available that can handle it. */
  999. STATIC int
  1000. needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
  1001. {
  1002. return (!circuit_all_predicted_ports_handled(now, needs_uptime,
  1003. needs_capacity) &&
  1004. router_have_consensus_path() == CONSENSUS_PATH_EXIT);
  1005. }
  1006. /* Hidden services need at least this many internal circuits */
  1007. #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
  1008. /* Return true if we need any more hidden service server circuits.
  1009. * HS servers only need an internal circuit. */
  1010. STATIC int
  1011. needs_hs_server_circuits(time_t now, int num_uptime_internal)
  1012. {
  1013. if (!rend_num_services() && !hs_service_get_num_services()) {
  1014. /* No services, we don't need anything. */
  1015. goto no_need;
  1016. }
  1017. if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
  1018. /* We have sufficient amount of internal circuit. */
  1019. goto no_need;
  1020. }
  1021. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
  1022. /* Consensus hasn't been checked or might be invalid so requesting
  1023. * internal circuits is not wise. */
  1024. goto no_need;
  1025. }
  1026. /* At this point, we need a certain amount of circuits and we will most
  1027. * likely use them for rendezvous so we note down the use of internal
  1028. * circuit for our prediction for circuit needing uptime and capacity. */
  1029. rep_hist_note_used_internal(now, 1, 1);
  1030. return 1;
  1031. no_need:
  1032. return 0;
  1033. }
  1034. /* We need at least this many internal circuits for hidden service clients */
  1035. #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
  1036. /* We need at least this much uptime for internal circuits for hidden service
  1037. * clients */
  1038. #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
  1039. /* Return true if we need any more hidden service client circuits.
  1040. * HS clients only need an internal circuit. */
  1041. STATIC int
  1042. needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
  1043. int num_internal, int num_uptime_internal)
  1044. {
  1045. int used_internal_recently = rep_hist_get_predicted_internal(now,
  1046. needs_uptime,
  1047. needs_capacity);
  1048. int requires_uptime = num_uptime_internal <
  1049. SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
  1050. needs_uptime;
  1051. return (used_internal_recently &&
  1052. (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
  1053. router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
  1054. }
  1055. /* The minimum number of open slots we should keep in order to preemptively
  1056. * build circuits. */
  1057. #define CBT_MIN_REMAINING_PREEMPTIVE_CIRCUITS 2
  1058. /* Check to see if we need more circuits to have a good build timeout. However,
  1059. * leave a couple slots open so that we can still build circuits preemptively
  1060. * as needed. */
  1061. #define CBT_MAX_UNUSED_OPEN_CIRCUITS (MAX_UNUSED_OPEN_CIRCUITS - \
  1062. CBT_MIN_REMAINING_PREEMPTIVE_CIRCUITS)
  1063. /* Return true if we need more circuits for a good build timeout.
  1064. * XXXX make the assumption that build timeout streams should be
  1065. * created whenever we can build internal circuits. */
  1066. STATIC int
  1067. needs_circuits_for_build(int num)
  1068. {
  1069. if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
  1070. if (num < CBT_MAX_UNUSED_OPEN_CIRCUITS &&
  1071. !circuit_build_times_disabled(get_options()) &&
  1072. circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
  1073. return 1;
  1074. }
  1075. }
  1076. return 0;
  1077. }
  1078. /** Determine how many circuits we have open that are clean,
  1079. * Make sure it's enough for all the upcoming behaviors we predict we'll have.
  1080. * But put an upper bound on the total number of circuits.
  1081. */
  1082. static void
  1083. circuit_predict_and_launch_new(void)
  1084. {
  1085. int num=0, num_internal=0, num_uptime_internal=0;
  1086. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  1087. int port_needs_uptime=0, port_needs_capacity=1;
  1088. time_t now = time(NULL);
  1089. int flags = 0;
  1090. /* Count how many of each type of circuit we currently have. */
  1091. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1092. if (!circuit_is_available_for_use(circ))
  1093. continue;
  1094. num++;
  1095. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  1096. if (build_state->is_internal)
  1097. num_internal++;
  1098. if (build_state->need_uptime && build_state->is_internal)
  1099. num_uptime_internal++;
  1100. }
  1101. SMARTLIST_FOREACH_END(circ);
  1102. /* If that's enough, then stop now. */
  1103. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  1104. return;
  1105. if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
  1106. if (port_needs_uptime)
  1107. flags |= CIRCLAUNCH_NEED_UPTIME;
  1108. if (port_needs_capacity)
  1109. flags |= CIRCLAUNCH_NEED_CAPACITY;
  1110. log_info(LD_CIRC,
  1111. "Have %d clean circs (%d internal), need another exit circ.",
  1112. num, num_internal);
  1113. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1114. return;
  1115. }
  1116. if (needs_hs_server_circuits(now, num_uptime_internal)) {
  1117. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  1118. CIRCLAUNCH_IS_INTERNAL);
  1119. log_info(LD_CIRC,
  1120. "Have %d clean circs (%d internal), need another internal "
  1121. "circ for my hidden service.",
  1122. num, num_internal);
  1123. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1124. return;
  1125. }
  1126. if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
  1127. &hidserv_needs_capacity,
  1128. num_internal, num_uptime_internal))
  1129. {
  1130. if (hidserv_needs_uptime)
  1131. flags |= CIRCLAUNCH_NEED_UPTIME;
  1132. if (hidserv_needs_capacity)
  1133. flags |= CIRCLAUNCH_NEED_CAPACITY;
  1134. flags |= CIRCLAUNCH_IS_INTERNAL;
  1135. log_info(LD_CIRC,
  1136. "Have %d clean circs (%d uptime-internal, %d internal), need"
  1137. " another hidden service circ.",
  1138. num, num_uptime_internal, num_internal);
  1139. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1140. return;
  1141. }
  1142. if (needs_circuits_for_build(num)) {
  1143. flags = CIRCLAUNCH_NEED_CAPACITY;
  1144. /* if there are no exits in the consensus, make timeout
  1145. * circuits internal */
  1146. if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
  1147. flags |= CIRCLAUNCH_IS_INTERNAL;
  1148. log_info(LD_CIRC,
  1149. "Have %d clean circs need another buildtime test circ.", num);
  1150. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1151. return;
  1152. }
  1153. }
  1154. /** Build a new test circuit every 5 minutes */
  1155. #define TESTING_CIRCUIT_INTERVAL 300
  1156. /** This function is called once a second, if router_have_minimum_dir_info()
  1157. * is true. Its job is to make sure all services we offer have enough circuits
  1158. * available. Some services just want enough circuits for current tasks,
  1159. * whereas others want a minimum set of idle circuits hanging around.
  1160. */
  1161. void
  1162. circuit_build_needed_circs(time_t now)
  1163. {
  1164. const or_options_t *options = get_options();
  1165. /* launch a new circ for any pending streams that need one
  1166. * XXXX make the assumption that (some) AP streams (i.e. HS clients)
  1167. * don't require an exit circuit, review in #13814.
  1168. * This allows HSs to function in a consensus without exits. */
  1169. if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
  1170. connection_ap_rescan_and_attach_pending();
  1171. circuit_expire_old_circs_as_needed(now);
  1172. if (!options->DisablePredictedCircuits)
  1173. circuit_predict_and_launch_new();
  1174. }
  1175. /**
  1176. * Called once a second either directly or from
  1177. * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
  1178. * resets failure counts and expires old circuits.
  1179. */
  1180. void
  1181. circuit_expire_old_circs_as_needed(time_t now)
  1182. {
  1183. static time_t time_to_expire_and_reset = 0;
  1184. if (time_to_expire_and_reset < now) {
  1185. circuit_reset_failure_count(1);
  1186. time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
  1187. if (proxy_mode(get_options()))
  1188. addressmap_clean(now);
  1189. circuit_expire_old_circuits_clientside();
  1190. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  1191. /* If we ever re-enable, this has to move into
  1192. * circuit_build_needed_circs */
  1193. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  1194. if (get_options()->RunTesting &&
  1195. circ &&
  1196. circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
  1197. log_fn(LOG_INFO,"Creating a new testing circuit.");
  1198. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
  1199. }
  1200. #endif
  1201. }
  1202. }
  1203. /** If the stream <b>conn</b> is a member of any of the linked
  1204. * lists of <b>circ</b>, then remove it from the list.
  1205. */
  1206. void
  1207. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  1208. {
  1209. edge_connection_t *prevconn;
  1210. tor_assert(circ);
  1211. tor_assert(conn);
  1212. if (conn->base_.type == CONN_TYPE_AP) {
  1213. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1214. entry_conn->may_use_optimistic_data = 0;
  1215. }
  1216. conn->cpath_layer = NULL; /* don't keep a stale pointer */
  1217. conn->on_circuit = NULL;
  1218. if (CIRCUIT_IS_ORIGIN(circ)) {
  1219. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1220. int removed = 0;
  1221. if (conn == origin_circ->p_streams) {
  1222. origin_circ->p_streams = conn->next_stream;
  1223. removed = 1;
  1224. } else {
  1225. for (prevconn = origin_circ->p_streams;
  1226. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1227. prevconn = prevconn->next_stream)
  1228. ;
  1229. if (prevconn && prevconn->next_stream) {
  1230. prevconn->next_stream = conn->next_stream;
  1231. removed = 1;
  1232. }
  1233. }
  1234. if (removed) {
  1235. log_debug(LD_APP, "Removing stream %d from circ %u",
  1236. conn->stream_id, (unsigned)circ->n_circ_id);
  1237. /* If the stream was removed, and it was a rend stream, decrement the
  1238. * number of streams on the circuit associated with the rend service.
  1239. */
  1240. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1241. tor_assert(origin_circ->rend_data);
  1242. origin_circ->rend_data->nr_streams--;
  1243. }
  1244. return;
  1245. }
  1246. } else {
  1247. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1248. if (conn == or_circ->n_streams) {
  1249. or_circ->n_streams = conn->next_stream;
  1250. return;
  1251. }
  1252. if (conn == or_circ->resolving_streams) {
  1253. or_circ->resolving_streams = conn->next_stream;
  1254. return;
  1255. }
  1256. for (prevconn = or_circ->n_streams;
  1257. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1258. prevconn = prevconn->next_stream)
  1259. ;
  1260. if (prevconn && prevconn->next_stream) {
  1261. prevconn->next_stream = conn->next_stream;
  1262. return;
  1263. }
  1264. for (prevconn = or_circ->resolving_streams;
  1265. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1266. prevconn = prevconn->next_stream)
  1267. ;
  1268. if (prevconn && prevconn->next_stream) {
  1269. prevconn->next_stream = conn->next_stream;
  1270. return;
  1271. }
  1272. }
  1273. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  1274. /* Don't give an error here; it's harmless. */
  1275. tor_fragile_assert();
  1276. }
  1277. /** Find each circuit that has been unused for too long, or dirty
  1278. * for too long and has no streams on it: mark it for close.
  1279. */
  1280. static void
  1281. circuit_expire_old_circuits_clientside(void)
  1282. {
  1283. struct timeval cutoff, now;
  1284. tor_gettimeofday(&now);
  1285. last_expired_clientside_circuits = now.tv_sec;
  1286. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1287. if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
  1288. continue;
  1289. cutoff = now;
  1290. cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
  1291. /* If the circuit has been dirty for too long, and there are no streams
  1292. * on it, mark it for close.
  1293. */
  1294. if (circ->timestamp_dirty &&
  1295. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
  1296. now.tv_sec &&
  1297. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  1298. log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
  1299. "purpose %d)",
  1300. (unsigned)circ->n_circ_id,
  1301. (long)(now.tv_sec - circ->timestamp_dirty),
  1302. circ->purpose);
  1303. /* Don't do this magic for testing circuits. Their death is governed
  1304. * by circuit_expire_building */
  1305. if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
  1306. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1307. } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
  1308. if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
  1309. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  1310. circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
  1311. circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1312. circ->purpose == CIRCUIT_PURPOSE_TESTING ||
  1313. (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1314. circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
  1315. circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  1316. log_info(LD_CIRC,
  1317. "Closing circuit "U64_FORMAT
  1318. " that has been unused for %ld msec.",
  1319. U64_PRINTF_ARG(TO_ORIGIN_CIRCUIT(circ)->global_identifier),
  1320. tv_mdiff(&circ->timestamp_began, &now));
  1321. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1322. } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
  1323. /* Server-side rend joined circuits can end up really old, because
  1324. * they are reused by clients for longer than normal. The client
  1325. * controls their lifespan. (They never become dirty, because
  1326. * connection_exit_begin_conn() never marks anything as dirty.)
  1327. * Similarly, server-side intro circuits last a long time. */
  1328. if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
  1329. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1330. log_notice(LD_CIRC,
  1331. "Ancient non-dirty circuit %d is still around after "
  1332. "%ld milliseconds. Purpose: %d (%s)",
  1333. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1334. tv_mdiff(&circ->timestamp_began, &now),
  1335. circ->purpose,
  1336. circuit_purpose_to_string(circ->purpose));
  1337. TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
  1338. }
  1339. }
  1340. }
  1341. }
  1342. } SMARTLIST_FOREACH_END(circ);
  1343. }
  1344. /** How long do we wait before killing circuits with the properties
  1345. * described below?
  1346. *
  1347. * Probably we could choose a number here as low as 5 to 10 seconds,
  1348. * since these circs are used for begindir, and a) generally you either
  1349. * ask another begindir question right after or you don't for a long time,
  1350. * b) clients at least through 0.2.1.x choose from the whole set of
  1351. * directory mirrors at each choice, and c) re-establishing a one-hop
  1352. * circuit via create-fast is a light operation assuming the TLS conn is
  1353. * still there.
  1354. *
  1355. * I expect "b" to go away one day when we move to using directory
  1356. * guards, but I think "a" and "c" are good enough reasons that a low
  1357. * number is safe even then.
  1358. */
  1359. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  1360. /** Find each non-origin circuit that has been unused for too long,
  1361. * has no streams on it, used a create_fast, and ends here: mark it
  1362. * for close.
  1363. */
  1364. void
  1365. circuit_expire_old_circuits_serverside(time_t now)
  1366. {
  1367. or_circuit_t *or_circ;
  1368. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  1369. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1370. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  1371. continue;
  1372. or_circ = TO_OR_CIRCUIT(circ);
  1373. /* If the circuit has been idle for too long, and there are no streams
  1374. * on it, and it ends here, and it used a create_fast, mark it for close.
  1375. */
  1376. if (or_circ->is_first_hop && !circ->n_chan &&
  1377. !or_circ->n_streams && !or_circ->resolving_streams &&
  1378. or_circ->p_chan &&
  1379. channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
  1380. log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
  1381. (unsigned)or_circ->p_circ_id,
  1382. (int)(now - channel_when_last_xmit(or_circ->p_chan)));
  1383. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1384. }
  1385. }
  1386. SMARTLIST_FOREACH_END(circ);
  1387. }
  1388. /** Number of testing circuits we want open before testing our bandwidth. */
  1389. #define NUM_PARALLEL_TESTING_CIRCS 4
  1390. /** True iff we've ever had enough testing circuits open to test our
  1391. * bandwidth. */
  1392. static int have_performed_bandwidth_test = 0;
  1393. /** Reset have_performed_bandwidth_test, so we'll start building
  1394. * testing circuits again so we can exercise our bandwidth. */
  1395. void
  1396. reset_bandwidth_test(void)
  1397. {
  1398. have_performed_bandwidth_test = 0;
  1399. }
  1400. /** Return 1 if we've already exercised our bandwidth, or if we
  1401. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  1402. * established or on the way. Else return 0.
  1403. */
  1404. int
  1405. circuit_enough_testing_circs(void)
  1406. {
  1407. int num = 0;
  1408. if (have_performed_bandwidth_test)
  1409. return 1;
  1410. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1411. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  1412. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  1413. circ->state == CIRCUIT_STATE_OPEN)
  1414. num++;
  1415. }
  1416. SMARTLIST_FOREACH_END(circ);
  1417. return num >= NUM_PARALLEL_TESTING_CIRCS;
  1418. }
  1419. /** A testing circuit has completed. Take whatever stats we want.
  1420. * Noticing reachability is taken care of in onionskin_answer(),
  1421. * so there's no need to record anything here. But if we still want
  1422. * to do the bandwidth test, and we now have enough testing circuits
  1423. * open, do it.
  1424. */
  1425. static void
  1426. circuit_testing_opened(origin_circuit_t *circ)
  1427. {
  1428. if (have_performed_bandwidth_test ||
  1429. !check_whether_orport_reachable(get_options())) {
  1430. /* either we've already done everything we want with testing circuits,
  1431. * or this testing circuit became open due to a fluke, e.g. we picked
  1432. * a last hop where we already had the connection open due to an
  1433. * outgoing local circuit. */
  1434. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1435. } else if (circuit_enough_testing_circs()) {
  1436. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  1437. have_performed_bandwidth_test = 1;
  1438. } else
  1439. consider_testing_reachability(1, 0);
  1440. }
  1441. /** A testing circuit has failed to build. Take whatever stats we want. */
  1442. static void
  1443. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  1444. {
  1445. const or_options_t *options = get_options();
  1446. if (server_mode(options) && check_whether_orport_reachable(options))
  1447. return;
  1448. log_info(LD_GENERAL,
  1449. "Our testing circuit (to see if your ORPort is reachable) "
  1450. "has failed. I'll try again later.");
  1451. /* These aren't used yet. */
  1452. (void)circ;
  1453. (void)at_last_hop;
  1454. }
  1455. /** The circuit <b>circ</b> has just become open. Take the next
  1456. * step: for rendezvous circuits, we pass circ to the appropriate
  1457. * function in rendclient or rendservice. For general circuits, we
  1458. * call connection_ap_attach_pending, which looks for pending streams
  1459. * that could use circ.
  1460. */
  1461. void
  1462. circuit_has_opened(origin_circuit_t *circ)
  1463. {
  1464. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  1465. /* Remember that this circuit has finished building. Now if we start
  1466. * it building again later (e.g. by extending it), we will know not
  1467. * to consider its build time. */
  1468. circ->has_opened = 1;
  1469. switch (TO_CIRCUIT(circ)->purpose) {
  1470. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1471. rend_client_rendcirc_has_opened(circ);
  1472. /* Start building an intro circ if we don't have one yet. */
  1473. connection_ap_attach_pending(1);
  1474. /* This isn't a call to circuit_try_attaching_streams because a
  1475. * circuit in _C_ESTABLISH_REND state isn't connected to its
  1476. * hidden service yet, thus we can't attach streams to it yet,
  1477. * thus circuit_try_attaching_streams would always clear the
  1478. * circuit's isolation state. circuit_try_attaching_streams is
  1479. * called later, when the rend circ enters _C_REND_JOINED
  1480. * state. */
  1481. break;
  1482. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1483. rend_client_introcirc_has_opened(circ);
  1484. break;
  1485. case CIRCUIT_PURPOSE_C_GENERAL:
  1486. /* Tell any AP connections that have been waiting for a new
  1487. * circuit that one is ready. */
  1488. circuit_try_attaching_streams(circ);
  1489. break;
  1490. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1491. /* at the service, waiting for introductions */
  1492. hs_service_circuit_has_opened(circ);
  1493. break;
  1494. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1495. /* at the service, connecting to rend point */
  1496. hs_service_circuit_has_opened(circ);
  1497. break;
  1498. case CIRCUIT_PURPOSE_TESTING:
  1499. circuit_testing_opened(circ);
  1500. break;
  1501. /* default:
  1502. * This won't happen in normal operation, but might happen if the
  1503. * controller did it. Just let it slide. */
  1504. }
  1505. }
  1506. /** If the stream-isolation state of <b>circ</b> can be cleared, clear
  1507. * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
  1508. static int
  1509. circuit_try_clearing_isolation_state(origin_circuit_t *circ)
  1510. {
  1511. if (/* The circuit may have become non-open if it was cannibalized.*/
  1512. circ->base_.state == CIRCUIT_STATE_OPEN &&
  1513. /* If !isolation_values_set, there is nothing to clear. */
  1514. circ->isolation_values_set &&
  1515. /* It's not legal to clear a circuit's isolation info if it's ever had
  1516. * streams attached */
  1517. !circ->isolation_any_streams_attached) {
  1518. /* If we have any isolation information set on this circuit, and
  1519. * we didn't manage to attach any streams to it, then we can
  1520. * and should clear it and try again. */
  1521. circuit_clear_isolation(circ);
  1522. return 1;
  1523. } else {
  1524. return 0;
  1525. }
  1526. }
  1527. /** Called when a circuit becomes ready for streams to be attached to
  1528. * it. */
  1529. void
  1530. circuit_try_attaching_streams(origin_circuit_t *circ)
  1531. {
  1532. /* Attach streams to this circuit if we can. */
  1533. connection_ap_attach_pending(1);
  1534. /* The call to circuit_try_clearing_isolation_state here will do
  1535. * nothing and return 0 if we didn't attach any streams to circ
  1536. * above. */
  1537. if (circuit_try_clearing_isolation_state(circ)) {
  1538. /* Maybe *now* we can attach some streams to this circuit. */
  1539. connection_ap_attach_pending(1);
  1540. }
  1541. }
  1542. /** Called whenever a circuit could not be successfully built.
  1543. */
  1544. void
  1545. circuit_build_failed(origin_circuit_t *circ)
  1546. {
  1547. channel_t *n_chan = NULL;
  1548. /* we should examine circ and see if it failed because of
  1549. * the last hop or an earlier hop. then use this info below.
  1550. */
  1551. int failed_at_last_hop = 0;
  1552. /* If the last hop isn't open, and the second-to-last is, we failed
  1553. * at the last hop. */
  1554. if (circ->cpath &&
  1555. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  1556. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  1557. failed_at_last_hop = 1;
  1558. }
  1559. if (circ->cpath &&
  1560. circ->cpath->state != CPATH_STATE_OPEN &&
  1561. ! circ->base_.received_destroy) {
  1562. /* We failed at the first hop for some reason other than a DESTROY cell.
  1563. * If there's an OR connection to blame, blame it. Also, avoid this relay
  1564. * for a while, and fail any one-hop directory fetches destined for it. */
  1565. const char *n_chan_id = circ->cpath->extend_info->identity_digest;
  1566. int already_marked = 0;
  1567. if (circ->base_.n_chan) {
  1568. n_chan = circ->base_.n_chan;
  1569. if (n_chan->is_bad_for_new_circs) {
  1570. /* We only want to blame this router when a fresh healthy
  1571. * connection fails. So don't mark this router as newly failed,
  1572. * since maybe this was just an old circuit attempt that's
  1573. * finally timing out now. Also, there's no need to blow away
  1574. * circuits/streams/etc, since the failure of an unhealthy conn
  1575. * doesn't tell us much about whether a healthy conn would
  1576. * succeed. */
  1577. already_marked = 1;
  1578. }
  1579. log_info(LD_OR,
  1580. "Our circuit failed to get a response from the first hop "
  1581. "(%s). I'm going to try to rotate to a better connection.",
  1582. channel_get_canonical_remote_descr(n_chan));
  1583. n_chan->is_bad_for_new_circs = 1;
  1584. } else {
  1585. log_info(LD_OR,
  1586. "Our circuit died before the first hop with no connection");
  1587. }
  1588. if (n_chan_id && !already_marked) {
  1589. /* New guard API: we failed. */
  1590. if (circ->guard_state)
  1591. entry_guard_failed(&circ->guard_state);
  1592. /* if there are any one-hop streams waiting on this circuit, fail
  1593. * them now so they can retry elsewhere. */
  1594. connection_ap_fail_onehop(n_chan_id, circ->build_state);
  1595. }
  1596. }
  1597. switch (circ->base_.purpose) {
  1598. case CIRCUIT_PURPOSE_C_GENERAL:
  1599. /* If we never built the circuit, note it as a failure. */
  1600. circuit_increment_failure_count();
  1601. if (failed_at_last_hop) {
  1602. /* Make sure any streams that demand our last hop as their exit
  1603. * know that it's unlikely to happen. */
  1604. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1605. }
  1606. break;
  1607. case CIRCUIT_PURPOSE_TESTING:
  1608. circuit_testing_failed(circ, failed_at_last_hop);
  1609. break;
  1610. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1611. /* at the service, waiting for introductions */
  1612. if (circ->base_.state != CIRCUIT_STATE_OPEN) {
  1613. circuit_increment_failure_count();
  1614. }
  1615. /* no need to care here, because the service will rebuild intro
  1616. * points periodically. */
  1617. break;
  1618. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1619. /* at the client, connecting to intro point */
  1620. /* Don't increment failure count, since the service may have picked
  1621. * the introduction point maliciously */
  1622. /* The client will pick a new intro point when this one dies, if
  1623. * the stream in question still cares. No need to act here. */
  1624. break;
  1625. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1626. /* at the client, waiting for the service */
  1627. circuit_increment_failure_count();
  1628. /* the client will pick a new rend point when this one dies, if
  1629. * the stream in question still cares. No need to act here. */
  1630. break;
  1631. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1632. /* at the service, connecting to rend point */
  1633. /* Don't increment failure count, since the client may have picked
  1634. * the rendezvous point maliciously */
  1635. log_info(LD_REND,
  1636. "Couldn't connect to the client's chosen rend point %s "
  1637. "(%s hop failed).",
  1638. escaped(build_state_get_exit_nickname(circ->build_state)),
  1639. failed_at_last_hop?"last":"non-last");
  1640. hs_circ_retry_service_rendezvous_point(circ);
  1641. break;
  1642. /* default:
  1643. * This won't happen in normal operation, but might happen if the
  1644. * controller did it. Just let it slide. */
  1645. }
  1646. }
  1647. /** Number of consecutive failures so far; should only be touched by
  1648. * circuit_launch_new and circuit_*_failure_count.
  1649. */
  1650. static int n_circuit_failures = 0;
  1651. /** Before the last time we called circuit_reset_failure_count(), were
  1652. * there a lot of failures? */
  1653. static int did_circs_fail_last_period = 0;
  1654. /** Don't retry launching a new circuit if we try this many times with no
  1655. * success. */
  1656. #define MAX_CIRCUIT_FAILURES 5
  1657. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1658. * details on arguments. */
  1659. origin_circuit_t *
  1660. circuit_launch(uint8_t purpose, int flags)
  1661. {
  1662. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1663. }
  1664. /* Do we have enough descriptors to build paths?
  1665. * If need_exit is true, return 1 if we can build exit paths.
  1666. * (We need at least one Exit in the consensus to build exit paths.)
  1667. * If need_exit is false, return 1 if we can build internal paths.
  1668. */
  1669. static int
  1670. have_enough_path_info(int need_exit)
  1671. {
  1672. if (need_exit)
  1673. return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
  1674. else
  1675. return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
  1676. }
  1677. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1678. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1679. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1680. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1681. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1682. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1683. * Return the newly allocated circuit on success, or NULL on failure. */
  1684. origin_circuit_t *
  1685. circuit_launch_by_extend_info(uint8_t purpose,
  1686. extend_info_t *extend_info,
  1687. int flags)
  1688. {
  1689. origin_circuit_t *circ;
  1690. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1691. int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
  1692. int need_specific_rp = 0;
  1693. if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
  1694. log_debug(LD_CIRC,"Haven't %s yet; canceling "
  1695. "circuit launch.",
  1696. !router_have_minimum_dir_info() ?
  1697. "fetched enough directory info" :
  1698. "received a consensus with exits");
  1699. return NULL;
  1700. }
  1701. /* If Tor2webRendezvousPoints is enabled and we are dealing with an
  1702. RP circuit, we want a specific RP node so we shouldn't canibalize
  1703. an already existing circuit. */
  1704. if (get_options()->Tor2webRendezvousPoints &&
  1705. purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  1706. need_specific_rp = 1;
  1707. }
  1708. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  1709. purpose != CIRCUIT_PURPOSE_TESTING &&
  1710. !onehop_tunnel && !need_specific_rp) {
  1711. /* see if there are appropriate circs available to cannibalize. */
  1712. /* XXX if we're planning to add a hop, perhaps we want to look for
  1713. * internal circs rather than exit circs? -RD */
  1714. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1715. if (circ) {
  1716. uint8_t old_purpose = circ->base_.purpose;
  1717. struct timeval old_timestamp_began = circ->base_.timestamp_began;
  1718. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
  1719. build_state_get_exit_nickname(circ->build_state), purpose,
  1720. circuit_purpose_to_string(purpose));
  1721. if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1722. purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
  1723. circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1724. /* Path bias: Cannibalized rends pre-emptively count as a
  1725. * successfully built but unused closed circuit. We don't
  1726. * wait until the extend (or the close) because the rend
  1727. * point could be malicious.
  1728. *
  1729. * Same deal goes for client side introductions. Clients
  1730. * can be manipulated to connect repeatedly to them
  1731. * (especially web clients).
  1732. *
  1733. * If we decide to probe the initial portion of these circs,
  1734. * (up to the adversary's final hop), we need to remove this,
  1735. * or somehow mark the circuit with a special path state.
  1736. */
  1737. /* This must be called before the purpose change */
  1738. pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
  1739. }
  1740. circuit_change_purpose(TO_CIRCUIT(circ), purpose);
  1741. /* Reset the start date of this circ, else expire_building
  1742. * will see it and think it's been trying to build since it
  1743. * began.
  1744. *
  1745. * Technically, the code should reset this when the
  1746. * create cell is finally sent, but we're close enough
  1747. * here. */
  1748. tor_gettimeofday(&circ->base_.timestamp_began);
  1749. control_event_circuit_cannibalized(circ, old_purpose,
  1750. &old_timestamp_began);
  1751. switch (purpose) {
  1752. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1753. /* it's ready right now */
  1754. break;
  1755. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1756. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1757. case CIRCUIT_PURPOSE_C_GENERAL:
  1758. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1759. /* need to add a new hop */
  1760. tor_assert(extend_info);
  1761. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1762. return NULL;
  1763. break;
  1764. default:
  1765. log_warn(LD_BUG,
  1766. "unexpected purpose %d when cannibalizing a circ.",
  1767. purpose);
  1768. tor_fragile_assert();
  1769. return NULL;
  1770. }
  1771. return circ;
  1772. }
  1773. }
  1774. if (did_circs_fail_last_period &&
  1775. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1776. /* too many failed circs in a row. don't try. */
  1777. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1778. return NULL;
  1779. }
  1780. /* try a circ. if it fails, circuit_mark_for_close will increment
  1781. * n_circuit_failures */
  1782. return circuit_establish_circuit(purpose, extend_info, flags);
  1783. }
  1784. /** Record another failure at opening a general circuit. When we have
  1785. * too many, we'll stop trying for the remainder of this minute.
  1786. */
  1787. static void
  1788. circuit_increment_failure_count(void)
  1789. {
  1790. ++n_circuit_failures;
  1791. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1792. }
  1793. /** Reset the failure count for opening general circuits. This means
  1794. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1795. * stopping again.
  1796. */
  1797. void
  1798. circuit_reset_failure_count(int timeout)
  1799. {
  1800. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1801. did_circs_fail_last_period = 1;
  1802. else
  1803. did_circs_fail_last_period = 0;
  1804. n_circuit_failures = 0;
  1805. }
  1806. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1807. * there isn't one, and there isn't one on the way, launch one and return
  1808. * 0. If it will never work, return -1.
  1809. *
  1810. * Write the found or in-progress or launched circ into *circp.
  1811. */
  1812. static int
  1813. circuit_get_open_circ_or_launch(entry_connection_t *conn,
  1814. uint8_t desired_circuit_purpose,
  1815. origin_circuit_t **circp)
  1816. {
  1817. origin_circuit_t *circ;
  1818. int check_exit_policy;
  1819. int need_uptime, need_internal;
  1820. int want_onehop;
  1821. const or_options_t *options = get_options();
  1822. tor_assert(conn);
  1823. tor_assert(circp);
  1824. if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  1825. connection_t *c = ENTRY_TO_CONN(conn);
  1826. log_err(LD_BUG, "Connection state mismatch: wanted "
  1827. "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
  1828. c->state, conn_state_to_string(c->type, c->state));
  1829. }
  1830. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1831. /* Will the exit policy of the exit node apply to this stream? */
  1832. check_exit_policy =
  1833. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1834. !conn->use_begindir &&
  1835. !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
  1836. /* Does this connection want a one-hop circuit? */
  1837. want_onehop = conn->want_onehop;
  1838. /* Do we need a high-uptime circuit? */
  1839. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1840. smartlist_contains_int_as_string(options->LongLivedPorts,
  1841. conn->socks_request->port);
  1842. /* Do we need an "internal" circuit? */
  1843. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1844. need_internal = 1;
  1845. else if (conn->use_begindir || conn->want_onehop)
  1846. need_internal = 1;
  1847. else
  1848. need_internal = 0;
  1849. /* We now know what kind of circuit we need. See if there is an
  1850. * open circuit that we can use for this stream */
  1851. circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
  1852. desired_circuit_purpose,
  1853. need_uptime, need_internal);
  1854. if (circ) {
  1855. /* We got a circuit that will work for this stream! We can return it. */
  1856. *circp = circ;
  1857. return 1; /* we're happy */
  1858. }
  1859. /* Okay, there's no circuit open that will work for this stream. Let's
  1860. * see if there's an in-progress circuit or if we have to launch one */
  1861. /* Do we know enough directory info to build circuits at all? */
  1862. int have_path = have_enough_path_info(!need_internal);
  1863. if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
  1864. /* If we don't have enough directory information, we can't build
  1865. * multihop circuits.
  1866. */
  1867. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  1868. int severity = LOG_NOTICE;
  1869. /* Retry some stuff that might help the connection work. */
  1870. if (entry_list_is_constrained(options) &&
  1871. guards_retry_optimistic(options)) {
  1872. log_fn(severity, LD_APP|LD_DIR,
  1873. "Application request when we haven't %s. "
  1874. "Optimistically trying known %s again.",
  1875. !router_have_minimum_dir_info() ?
  1876. "used client functionality lately" :
  1877. "received a consensus with exits",
  1878. options->UseBridges ? "bridges" : "entrynodes");
  1879. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  1880. log_fn(severity, LD_APP|LD_DIR,
  1881. "Application request when we haven't %s. "
  1882. "Optimistically trying directory fetches again.",
  1883. !router_have_minimum_dir_info() ?
  1884. "used client functionality lately" :
  1885. "received a consensus with exits");
  1886. routerlist_retry_directory_downloads(time(NULL));
  1887. }
  1888. }
  1889. /* Since we didn't have enough directory info, we can't attach now. The
  1890. * stream will be dealt with when router_have_minimum_dir_info becomes 1,
  1891. * or when all directory attempts fail and directory_all_unreachable()
  1892. * kills it.
  1893. */
  1894. return 0;
  1895. }
  1896. /* Check whether the exit policy of the chosen exit, or the exit policies
  1897. * of _all_ nodes, would forbid this node. */
  1898. if (check_exit_policy) {
  1899. if (!conn->chosen_exit_name) {
  1900. struct in_addr in;
  1901. tor_addr_t addr, *addrp=NULL;
  1902. if (tor_inet_aton(conn->socks_request->address, &in)) {
  1903. tor_addr_from_in(&addr, &in);
  1904. addrp = &addr;
  1905. }
  1906. if (router_exit_policy_all_nodes_reject(addrp,
  1907. conn->socks_request->port,
  1908. need_uptime)) {
  1909. log_notice(LD_APP,
  1910. "No Tor server allows exit to %s:%d. Rejecting.",
  1911. safe_str_client(conn->socks_request->address),
  1912. conn->socks_request->port);
  1913. return -1;
  1914. }
  1915. } else {
  1916. /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
  1917. * refactor into a single function. */
  1918. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1919. int opt = conn->chosen_exit_optional;
  1920. if (node && !connection_ap_can_use_exit(conn, node)) {
  1921. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1922. "Requested exit point '%s' is excluded or "
  1923. "would refuse request. %s.",
  1924. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1925. if (opt) {
  1926. conn->chosen_exit_optional = 0;
  1927. tor_free(conn->chosen_exit_name);
  1928. /* Try again. */
  1929. return circuit_get_open_circ_or_launch(conn,
  1930. desired_circuit_purpose,
  1931. circp);
  1932. }
  1933. return -1;
  1934. }
  1935. }
  1936. }
  1937. /* Now, check whether there already a circuit on the way that could handle
  1938. * this stream. This check matches the one above, but this time we
  1939. * do not require that the circuit will work. */
  1940. circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
  1941. desired_circuit_purpose,
  1942. need_uptime, need_internal);
  1943. if (circ)
  1944. log_debug(LD_CIRC, "one on the way!");
  1945. if (!circ) {
  1946. /* No open or in-progress circuit could handle this stream! We
  1947. * will have to launch one!
  1948. */
  1949. /* The chosen exit node, if there is one. */
  1950. extend_info_t *extend_info=NULL;
  1951. const int n_pending = count_pending_general_client_circuits();
  1952. /* Do we have too many pending circuits? */
  1953. if (n_pending >= options->MaxClientCircuitsPending) {
  1954. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  1955. char *m;
  1956. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  1957. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  1958. "connection, but we already have %d general-purpose client "
  1959. "circuits pending. Waiting until some finish.%s",
  1960. n_pending, m);
  1961. tor_free(m);
  1962. }
  1963. return 0;
  1964. }
  1965. /* If this is a hidden service trying to start an introduction point,
  1966. * handle that case. */
  1967. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1968. /* need to pick an intro point */
  1969. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  1970. tor_assert(rend_data);
  1971. extend_info = rend_client_get_random_intro(rend_data);
  1972. if (!extend_info) {
  1973. log_info(LD_REND,
  1974. "No intro points for '%s': re-fetching service descriptor.",
  1975. safe_str_client(rend_data_get_address(rend_data)));
  1976. rend_client_refetch_v2_renddesc(rend_data);
  1977. connection_ap_mark_as_non_pending_circuit(conn);
  1978. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  1979. return 0;
  1980. }
  1981. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  1982. extend_info_describe(extend_info),
  1983. safe_str_client(rend_data_get_address(rend_data)));
  1984. }
  1985. /* If we have specified a particular exit node for our
  1986. * connection, then be sure to open a circuit to that exit node.
  1987. */
  1988. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1989. if (conn->chosen_exit_name) {
  1990. const node_t *r;
  1991. int opt = conn->chosen_exit_optional;
  1992. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1993. if (r && node_has_descriptor(r)) {
  1994. /* We might want to connect to an IPv6 bridge for loading
  1995. descriptors so we use the preferred address rather than
  1996. the primary. */
  1997. extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
  1998. if (!extend_info) {
  1999. log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
  2000. "Discarding this circuit.", conn->chosen_exit_name);
  2001. return -1;
  2002. }
  2003. } else { /* ! (r && node_has_descriptor(r)) */
  2004. log_debug(LD_DIR, "considering %d, %s",
  2005. want_onehop, conn->chosen_exit_name);
  2006. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  2007. /* We're asking for a one-hop circuit to a router that
  2008. * we don't have a routerinfo about. Make up an extend_info. */
  2009. /* XXX prop220: we need to make chosen_exit_name able to
  2010. * encode both key formats. This is not absolutely critical
  2011. * since this is just for one-hop circuits, but we should
  2012. * still get it done */
  2013. char digest[DIGEST_LEN];
  2014. char *hexdigest = conn->chosen_exit_name+1;
  2015. tor_addr_t addr;
  2016. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2017. base16_decode(digest,DIGEST_LEN,
  2018. hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
  2019. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  2020. return -1;
  2021. }
  2022. if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
  2023. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  2024. escaped_safe_str_client(conn->socks_request->address));
  2025. return -1;
  2026. }
  2027. /* XXXX prop220 add a workaround for ed25519 ID below*/
  2028. extend_info = extend_info_new(conn->chosen_exit_name+1,
  2029. digest,
  2030. NULL, /* Ed25519 ID */
  2031. NULL, NULL, /* onion keys */
  2032. &addr, conn->socks_request->port);
  2033. } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
  2034. /* We will need an onion key for the router, and we
  2035. * don't have one. Refuse or relax requirements. */
  2036. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2037. "Requested exit point '%s' is not known. %s.",
  2038. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2039. if (opt) {
  2040. conn->chosen_exit_optional = 0;
  2041. tor_free(conn->chosen_exit_name);
  2042. /* Try again with no requested exit */
  2043. return circuit_get_open_circ_or_launch(conn,
  2044. desired_circuit_purpose,
  2045. circp);
  2046. }
  2047. return -1;
  2048. }
  2049. }
  2050. }
  2051. } /* Done checking for general circutis with chosen exits. */
  2052. /* What purpose do we need to launch this circuit with? */
  2053. uint8_t new_circ_purpose;
  2054. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  2055. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  2056. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  2057. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  2058. else
  2059. new_circ_purpose = desired_circuit_purpose;
  2060. #ifdef ENABLE_TOR2WEB_MODE
  2061. /* If tor2Web is on, then hidden service requests should be one-hop.
  2062. */
  2063. if (options->Tor2webMode &&
  2064. (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  2065. new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
  2066. want_onehop = 1;
  2067. }
  2068. #endif
  2069. /* Determine what kind of a circuit to launch, and actually launch it. */
  2070. {
  2071. int flags = CIRCLAUNCH_NEED_CAPACITY;
  2072. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  2073. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  2074. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  2075. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  2076. flags);
  2077. }
  2078. extend_info_free(extend_info);
  2079. /* Now trigger things that need to happen when we launch circuits */
  2080. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  2081. /* We just caused a circuit to get built because of this stream.
  2082. * If this stream has caused a _lot_ of circuits to be built, that's
  2083. * a bad sign: we should tell the user. */
  2084. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  2085. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  2086. log_info(LD_CIRC, "The application request to %s:%d has launched "
  2087. "%d circuits without finding one it likes.",
  2088. escaped_safe_str_client(conn->socks_request->address),
  2089. conn->socks_request->port,
  2090. conn->num_circuits_launched);
  2091. } else {
  2092. /* help predict this next time */
  2093. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  2094. if (circ) {
  2095. /* write the service_id into circ */
  2096. circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
  2097. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  2098. circ->base_.state == CIRCUIT_STATE_OPEN)
  2099. circuit_has_opened(circ);
  2100. }
  2101. }
  2102. } /* endif (!circ) */
  2103. /* We either found a good circuit, or launched a new circuit, or failed to
  2104. * do so. Report success, and delay. */
  2105. if (circ) {
  2106. /* Mark the circuit with the isolation fields for this connection.
  2107. * When the circuit arrives, we'll clear these flags: this is
  2108. * just some internal bookkeeping to make sure that we have
  2109. * launched enough circuits.
  2110. */
  2111. connection_edge_update_circuit_isolation(conn, circ, 0);
  2112. } else {
  2113. log_info(LD_APP,
  2114. "No safe circuit (purpose %d) ready for edge "
  2115. "connection; delaying.",
  2116. desired_circuit_purpose);
  2117. }
  2118. *circp = circ;
  2119. return 0;
  2120. }
  2121. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  2122. * <b>circ</b>. */
  2123. static int
  2124. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  2125. {
  2126. crypt_path_t *cpath, *cpath_next = NULL;
  2127. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  2128. cpath_next = cpath->next;
  2129. if (crypt_path == cpath)
  2130. return 1;
  2131. }
  2132. return 0;
  2133. }
  2134. /** Return true iff client-side optimistic data is supported. */
  2135. static int
  2136. optimistic_data_enabled(void)
  2137. {
  2138. const or_options_t *options = get_options();
  2139. if (options->OptimisticData < 0) {
  2140. /* Note: this default was 0 before #18815 was merged. We can't take the
  2141. * parameter out of the consensus until versions before that are all
  2142. * obsolete. */
  2143. const int32_t enabled =
  2144. networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
  2145. return (int)enabled;
  2146. }
  2147. return options->OptimisticData;
  2148. }
  2149. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  2150. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  2151. * hop in circ's cpath if <b>cpath</b> is NULL.
  2152. */
  2153. static void
  2154. link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
  2155. crypt_path_t *cpath)
  2156. {
  2157. const node_t *exitnode = NULL;
  2158. /* add it into the linked list of streams on this circuit */
  2159. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
  2160. (unsigned)circ->base_.n_circ_id);
  2161. /* reset it, so we can measure circ timeouts */
  2162. ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
  2163. ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
  2164. ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
  2165. /* assert_connection_ok(conn, time(NULL)); */
  2166. circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
  2167. if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
  2168. /* We are attaching a stream to a rendezvous circuit. That means
  2169. * that an attempt to connect to a hidden service just
  2170. * succeeded. Tell rendclient.c. */
  2171. hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
  2172. }
  2173. if (cpath) { /* we were given one; use it */
  2174. tor_assert(cpath_is_on_circuit(circ, cpath));
  2175. } else {
  2176. /* use the last hop in the circuit */
  2177. tor_assert(circ->cpath);
  2178. tor_assert(circ->cpath->prev);
  2179. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  2180. cpath = circ->cpath->prev;
  2181. }
  2182. ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
  2183. circ->isolation_any_streams_attached = 1;
  2184. connection_edge_update_circuit_isolation(apconn, circ, 0);
  2185. /* Compute the exitnode if possible, for logging below */
  2186. if (cpath->extend_info)
  2187. exitnode = node_get_by_id(cpath->extend_info->identity_digest);
  2188. /* See if we can use optimistic data on this circuit */
  2189. if (optimistic_data_enabled() &&
  2190. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  2191. circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
  2192. apconn->may_use_optimistic_data = 1;
  2193. else
  2194. apconn->may_use_optimistic_data = 0;
  2195. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  2196. "optimistic data for connection to %s",
  2197. circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
  2198. /* node_describe() does the right thing if exitnode is NULL */
  2199. safe_str_client(node_describe(exitnode)) :
  2200. "hidden service",
  2201. apconn->may_use_optimistic_data ? "does" : "doesn't",
  2202. safe_str_client(apconn->socks_request->address));
  2203. }
  2204. /** Return true iff <b>address</b> is matched by one of the entries in
  2205. * TrackHostExits. */
  2206. int
  2207. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  2208. {
  2209. if (!options->TrackHostExits)
  2210. return 0;
  2211. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  2212. if (cp[0] == '.') { /* match end */
  2213. if (cp[1] == '\0' ||
  2214. !strcasecmpend(address, cp) ||
  2215. !strcasecmp(address, &cp[1]))
  2216. return 1;
  2217. } else if (strcasecmp(cp, address) == 0) {
  2218. return 1;
  2219. }
  2220. } SMARTLIST_FOREACH_END(cp);
  2221. return 0;
  2222. }
  2223. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  2224. * the exit that we *did* choose for use by future connections to
  2225. * <b>conn</b>'s destination.
  2226. */
  2227. static void
  2228. consider_recording_trackhost(const entry_connection_t *conn,
  2229. const origin_circuit_t *circ)
  2230. {
  2231. const or_options_t *options = get_options();
  2232. char *new_address = NULL;
  2233. char fp[HEX_DIGEST_LEN+1];
  2234. /* Search the addressmap for this conn's destination. */
  2235. /* If they're not in the address map.. */
  2236. if (!options->TrackHostExits ||
  2237. addressmap_have_mapping(conn->socks_request->address,
  2238. options->TrackHostExitsExpire))
  2239. return; /* nothing to track, or already mapped */
  2240. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  2241. !circ->build_state->chosen_exit)
  2242. return;
  2243. /* write down the fingerprint of the chosen exit, not the nickname,
  2244. * because the chosen exit might not be named. */
  2245. base16_encode(fp, sizeof(fp),
  2246. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  2247. /* Add this exit/hostname pair to the addressmap. */
  2248. tor_asprintf(&new_address, "%s.%s.exit",
  2249. conn->socks_request->address, fp);
  2250. addressmap_register(conn->socks_request->address, new_address,
  2251. time(NULL) + options->TrackHostExitsExpire,
  2252. ADDRMAPSRC_TRACKEXIT, 0, 0);
  2253. }
  2254. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  2255. * begin or resolve cell as appropriate. Return values are as for
  2256. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  2257. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  2258. * <b>cpath</b> is NULL. */
  2259. int
  2260. connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
  2261. origin_circuit_t *circ,
  2262. crypt_path_t *cpath)
  2263. {
  2264. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2265. tor_assert(conn);
  2266. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  2267. base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  2268. tor_assert(conn->socks_request);
  2269. tor_assert(circ);
  2270. tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
  2271. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2272. if (!circ->base_.timestamp_dirty ||
  2273. ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
  2274. (conn->entry_cfg.socks_iso_keep_alive) &&
  2275. (conn->socks_request->usernamelen ||
  2276. conn->socks_request->passwordlen))) {
  2277. /* When stream isolation is in use and controlled by an application
  2278. * we are willing to keep using the stream. */
  2279. circ->base_.timestamp_dirty = approx_time();
  2280. }
  2281. pathbias_count_use_attempt(circ);
  2282. /* Now, actually link the connection. */
  2283. link_apconn_to_circ(conn, circ, cpath);
  2284. tor_assert(conn->socks_request);
  2285. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2286. if (!conn->use_begindir)
  2287. consider_recording_trackhost(conn, circ);
  2288. if (connection_ap_handshake_send_begin(conn) < 0)
  2289. return -1;
  2290. } else {
  2291. if (connection_ap_handshake_send_resolve(conn) < 0)
  2292. return -1;
  2293. }
  2294. return 1;
  2295. }
  2296. /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
  2297. * attach the stream, send appropriate cells, and return 1. Otherwise,
  2298. * try to launch new circuit(s) for the stream. If we can launch
  2299. * circuits, return 0. Otherwise, if we simply can't proceed with
  2300. * this stream, return -1. (conn needs to die, and is maybe already marked).
  2301. */
  2302. /* XXXX this function should mark for close whenever it returns -1;
  2303. * its callers shouldn't have to worry about that. */
  2304. int
  2305. connection_ap_handshake_attach_circuit(entry_connection_t *conn)
  2306. {
  2307. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2308. int retval;
  2309. int conn_age;
  2310. int want_onehop;
  2311. tor_assert(conn);
  2312. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2313. tor_assert(conn->socks_request);
  2314. want_onehop = conn->want_onehop;
  2315. conn_age = (int)(time(NULL) - base_conn->timestamp_created);
  2316. /* Is this connection so old that we should give up on it? */
  2317. if (conn_age >= get_options()->SocksTimeout) {
  2318. int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
  2319. LOG_INFO : LOG_NOTICE;
  2320. log_fn(severity, LD_APP,
  2321. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  2322. conn_age, safe_str_client(conn->socks_request->address),
  2323. conn->socks_request->port);
  2324. return -1;
  2325. }
  2326. /* We handle "general" (non-onion) connections much more straightforwardly.
  2327. */
  2328. if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
  2329. /* we're a general conn */
  2330. origin_circuit_t *circ=NULL;
  2331. /* Are we linked to a dir conn that aims to fetch a consensus?
  2332. * We check here because the conn might no longer be needed. */
  2333. if (base_conn->linked_conn &&
  2334. base_conn->linked_conn->type == CONN_TYPE_DIR &&
  2335. base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  2336. /* Yes we are. Is there a consensus fetch farther along than us? */
  2337. if (networkstatus_consensus_is_already_downloading(
  2338. TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
  2339. /* We're doing the "multiple consensus fetch attempts" game from
  2340. * proposal 210, and we're late to the party. Just close this conn.
  2341. * The circuit and TLS conn that we made will time out after a while
  2342. * if nothing else wants to use them. */
  2343. log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
  2344. "is already downloading.", base_conn->linked_conn->address);
  2345. return -1;
  2346. }
  2347. }
  2348. /* If we have a chosen exit, we need to use a circuit that's
  2349. * open to that exit. See what exit we meant, and whether we can use it.
  2350. */
  2351. if (conn->chosen_exit_name) {
  2352. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  2353. int opt = conn->chosen_exit_optional;
  2354. if (!node && !want_onehop) {
  2355. /* We ran into this warning when trying to extend a circuit to a
  2356. * hidden service directory for which we didn't have a router
  2357. * descriptor. See flyspray task 767 for more details. We should
  2358. * keep this in mind when deciding to use BEGIN_DIR cells for other
  2359. * directory requests as well. -KL*/
  2360. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2361. "Requested exit point '%s' is not known. %s.",
  2362. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2363. if (opt) {
  2364. /* If we are allowed to ignore the .exit request, do so */
  2365. conn->chosen_exit_optional = 0;
  2366. tor_free(conn->chosen_exit_name);
  2367. return 0;
  2368. }
  2369. return -1;
  2370. }
  2371. if (node && !connection_ap_can_use_exit(conn, node)) {
  2372. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2373. "Requested exit point '%s' is excluded or "
  2374. "would refuse request. %s.",
  2375. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2376. if (opt) {
  2377. /* If we are allowed to ignore the .exit request, do so */
  2378. conn->chosen_exit_optional = 0;
  2379. tor_free(conn->chosen_exit_name);
  2380. return 0;
  2381. }
  2382. return -1;
  2383. }
  2384. }
  2385. /* Find the circuit that we should use, if there is one. Otherwise
  2386. * launch it. */
  2387. retval = circuit_get_open_circ_or_launch(
  2388. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  2389. if (retval < 1) {
  2390. /* We were either told "-1" (complete failure) or 0 (circuit in
  2391. * progress); we can't attach this stream yet. */
  2392. return retval;
  2393. }
  2394. log_debug(LD_APP|LD_CIRC,
  2395. "Attaching apconn to circ %u (stream %d sec old).",
  2396. (unsigned)circ->base_.n_circ_id, conn_age);
  2397. /* print the circ's path, so clients can figure out which circs are
  2398. * sucking. */
  2399. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  2400. /* We have found a suitable circuit for our conn. Hurray. Do
  2401. * the attachment. */
  2402. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  2403. } else { /* we're a rendezvous conn */
  2404. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  2405. tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
  2406. /* start by finding a rendezvous circuit for us */
  2407. retval = circuit_get_open_circ_or_launch(
  2408. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  2409. if (retval < 0) return -1; /* failed */
  2410. if (retval > 0) {
  2411. tor_assert(rendcirc);
  2412. /* one is already established, attach */
  2413. log_info(LD_REND,
  2414. "rend joined circ %u already here. attaching. "
  2415. "(stream %d sec old)",
  2416. (unsigned)rendcirc->base_.n_circ_id, conn_age);
  2417. /* Mark rendezvous circuits as 'newly dirty' every time you use
  2418. * them, since the process of rebuilding a rendezvous circ is so
  2419. * expensive. There is a tradeoff between linkability and
  2420. * feasibility, at this point.
  2421. */
  2422. rendcirc->base_.timestamp_dirty = time(NULL);
  2423. /* We've also attempted to use them. If they fail, we need to
  2424. * probe them for path bias */
  2425. pathbias_count_use_attempt(rendcirc);
  2426. link_apconn_to_circ(conn, rendcirc, NULL);
  2427. if (connection_ap_handshake_send_begin(conn) < 0)
  2428. return 0; /* already marked, let them fade away */
  2429. return 1;
  2430. }
  2431. /* At this point we need to re-check the state, since it's possible that
  2432. * our call to circuit_get_open_circ_or_launch() changed the connection's
  2433. * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
  2434. * re-fetch the descriptor.
  2435. */
  2436. if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  2437. log_info(LD_REND, "This connection is no longer ready to attach; its "
  2438. "state changed."
  2439. "(We probably have to re-fetch its descriptor.)");
  2440. return 0;
  2441. }
  2442. if (rendcirc && (rendcirc->base_.purpose ==
  2443. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  2444. log_info(LD_REND,
  2445. "pending-join circ %u already here, with intro ack. "
  2446. "Stalling. (stream %d sec old)",
  2447. (unsigned)rendcirc->base_.n_circ_id, conn_age);
  2448. return 0;
  2449. }
  2450. /* it's on its way. find an intro circ. */
  2451. retval = circuit_get_open_circ_or_launch(
  2452. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  2453. if (retval < 0) return -1; /* failed */
  2454. if (retval > 0) {
  2455. /* one has already sent the intro. keep waiting. */
  2456. tor_assert(introcirc);
  2457. log_info(LD_REND, "Intro circ %u present and awaiting ack (rend %u). "
  2458. "Stalling. (stream %d sec old)",
  2459. (unsigned)introcirc->base_.n_circ_id,
  2460. rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0,
  2461. conn_age);
  2462. return 0;
  2463. }
  2464. /* now rendcirc and introcirc are each either undefined or not finished */
  2465. if (rendcirc && introcirc &&
  2466. rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  2467. log_info(LD_REND,
  2468. "ready rend circ %u already here (no intro-ack yet on "
  2469. "intro %u). (stream %d sec old)",
  2470. (unsigned)rendcirc->base_.n_circ_id,
  2471. (unsigned)introcirc->base_.n_circ_id, conn_age);
  2472. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  2473. if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
  2474. log_info(LD_REND,"found open intro circ %u (rend %u); sending "
  2475. "introduction. (stream %d sec old)",
  2476. (unsigned)introcirc->base_.n_circ_id,
  2477. (unsigned)rendcirc->base_.n_circ_id,
  2478. conn_age);
  2479. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  2480. case 0: /* success */
  2481. rendcirc->base_.timestamp_dirty = time(NULL);
  2482. introcirc->base_.timestamp_dirty = time(NULL);
  2483. pathbias_count_use_attempt(introcirc);
  2484. pathbias_count_use_attempt(rendcirc);
  2485. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  2486. assert_circuit_ok(TO_CIRCUIT(introcirc));
  2487. return 0;
  2488. case -1: /* transient error */
  2489. return 0;
  2490. case -2: /* permanent error */
  2491. return -1;
  2492. default: /* oops */
  2493. tor_fragile_assert();
  2494. return -1;
  2495. }
  2496. }
  2497. }
  2498. log_info(LD_REND, "Intro (%u) and rend (%u) circs are not both ready. "
  2499. "Stalling conn. (%d sec old)",
  2500. introcirc ? (unsigned)introcirc->base_.n_circ_id : 0,
  2501. rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0, conn_age);
  2502. return 0;
  2503. }
  2504. }
  2505. /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
  2506. void
  2507. circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
  2508. {
  2509. uint8_t old_purpose;
  2510. /* Don't allow an OR circ to become an origin circ or vice versa. */
  2511. tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
  2512. !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
  2513. if (circ->purpose == new_purpose) return;
  2514. if (CIRCUIT_IS_ORIGIN(circ)) {
  2515. char old_purpose_desc[80] = "";
  2516. strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
  2517. old_purpose_desc[80-1] = '\0';
  2518. log_debug(LD_CIRC,
  2519. "changing purpose of origin circ %d "
  2520. "from \"%s\" (%d) to \"%s\" (%d)",
  2521. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  2522. old_purpose_desc,
  2523. circ->purpose,
  2524. circuit_purpose_to_string(new_purpose),
  2525. new_purpose);
  2526. }
  2527. old_purpose = circ->purpose;
  2528. circ->purpose = new_purpose;
  2529. if (CIRCUIT_IS_ORIGIN(circ)) {
  2530. control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
  2531. old_purpose);
  2532. }
  2533. }
  2534. /** Mark <b>circ</b> so that no more connections can be attached to it. */
  2535. void
  2536. mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
  2537. {
  2538. const or_options_t *options = get_options();
  2539. tor_assert(circ);
  2540. /* XXXX This is a kludge; we're only keeping it around in case there's
  2541. * something that doesn't check unusable_for_new_conns, and to avoid
  2542. * deeper refactoring of our expiration logic. */
  2543. if (! circ->base_.timestamp_dirty)
  2544. circ->base_.timestamp_dirty = approx_time();
  2545. if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
  2546. circ->base_.timestamp_dirty = 1; /* prevent underflow */
  2547. else
  2548. circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
  2549. circ->unusable_for_new_conns = 1;
  2550. }