circuitbuild.c 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849
  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-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #include "or.h"
  11. #include "channel.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuitstats.h"
  15. #include "circuituse.h"
  16. #include "command.h"
  17. #include "config.h"
  18. #include "confparse.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "directory.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "onion.h"
  29. #include "policies.h"
  30. #include "transports.h"
  31. #include "relay.h"
  32. #include "rephist.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. #include "routerset.h"
  37. #include "crypto.h"
  38. #ifndef MIN
  39. #define MIN(a,b) ((a)<(b)?(a):(b))
  40. #endif
  41. /********* START VARIABLES **********/
  42. /** A global list of all circuits at this hop. */
  43. extern circuit_t *global_circuitlist;
  44. /********* END VARIABLES ************/
  45. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  46. uint16_t port,
  47. const char *id_digest);
  48. static int circuit_deliver_create_cell(circuit_t *circ,
  49. uint8_t cell_type, const char *payload);
  50. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  51. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  52. static int onion_extend_cpath(origin_circuit_t *circ);
  53. static int count_acceptable_nodes(smartlist_t *routers);
  54. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  55. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  56. static void pathbias_count_build_success(origin_circuit_t *circ);
  57. static void pathbias_count_successful_close(origin_circuit_t *circ);
  58. static void pathbias_count_collapse(origin_circuit_t *circ);
  59. static void pathbias_count_unusable(origin_circuit_t *circ);
  60. /** This function tries to get a channel to the specified endpoint,
  61. * and then calls command_setup_channel() to give it the right
  62. * callbacks.
  63. */
  64. static channel_t *
  65. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  66. const char *id_digest)
  67. {
  68. channel_t *chan;
  69. chan = channel_connect(addr, port, id_digest);
  70. if (chan) command_setup_channel(chan);
  71. return chan;
  72. }
  73. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  74. * and with the high bit specified by conn-\>circ_id_type, until we get
  75. * a circ_id that is not in use by any other circuit on that conn.
  76. *
  77. * Return it, or 0 if can't get a unique circ_id.
  78. */
  79. static circid_t
  80. get_unique_circ_id_by_chan(channel_t *chan)
  81. {
  82. circid_t test_circ_id;
  83. circid_t attempts=0;
  84. circid_t high_bit;
  85. tor_assert(chan);
  86. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  87. log_warn(LD_BUG,
  88. "Trying to pick a circuit ID for a connection from "
  89. "a client with no identity.");
  90. return 0;
  91. }
  92. high_bit =
  93. (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  94. do {
  95. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  96. * circID such that (high_bit|test_circ_id) is not already used. */
  97. test_circ_id = chan->next_circ_id++;
  98. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  99. test_circ_id = 1;
  100. chan->next_circ_id = 2;
  101. }
  102. if (++attempts > 1<<15) {
  103. /* Make sure we don't loop forever if all circ_id's are used. This
  104. * matters because it's an external DoS opportunity.
  105. */
  106. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  107. return 0;
  108. }
  109. test_circ_id |= high_bit;
  110. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  111. return test_circ_id;
  112. }
  113. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  114. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  115. * list information about link status in a more verbose format using spaces.
  116. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  117. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  118. * names.
  119. */
  120. static char *
  121. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  122. {
  123. crypt_path_t *hop;
  124. smartlist_t *elements;
  125. const char *states[] = {"closed", "waiting for keys", "open"};
  126. char *s;
  127. elements = smartlist_new();
  128. if (verbose) {
  129. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  130. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  131. circ->build_state->is_internal ? "internal" : "exit",
  132. circ->build_state->need_uptime ? " (high-uptime)" : "",
  133. circ->build_state->desired_path_len,
  134. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  135. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  136. (nickname?nickname:"*unnamed*"));
  137. }
  138. hop = circ->cpath;
  139. do {
  140. char *elt;
  141. const char *id;
  142. const node_t *node;
  143. if (!hop)
  144. break;
  145. if (!verbose && hop->state != CPATH_STATE_OPEN)
  146. break;
  147. if (!hop->extend_info)
  148. break;
  149. id = hop->extend_info->identity_digest;
  150. if (verbose_names) {
  151. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  152. if ((node = node_get_by_id(id))) {
  153. node_get_verbose_nickname(node, elt);
  154. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  155. elt[0] = '$';
  156. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  157. elt[HEX_DIGEST_LEN+1]= '~';
  158. strlcpy(elt+HEX_DIGEST_LEN+2,
  159. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  160. } else {
  161. elt[0] = '$';
  162. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  163. }
  164. } else { /* ! verbose_names */
  165. node = node_get_by_id(id);
  166. if (node && node_is_named(node)) {
  167. elt = tor_strdup(node_get_nickname(node));
  168. } else {
  169. elt = tor_malloc(HEX_DIGEST_LEN+2);
  170. elt[0] = '$';
  171. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  172. }
  173. }
  174. tor_assert(elt);
  175. if (verbose) {
  176. tor_assert(hop->state <= 2);
  177. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  178. tor_free(elt);
  179. } else {
  180. smartlist_add(elements, elt);
  181. }
  182. hop = hop->next;
  183. } while (hop != circ->cpath);
  184. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  185. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  186. smartlist_free(elements);
  187. return s;
  188. }
  189. /** If <b>verbose</b> is false, allocate and return a comma-separated
  190. * list of the currently built elements of <b>circ</b>. If
  191. * <b>verbose</b> is true, also list information about link status in
  192. * a more verbose format using spaces.
  193. */
  194. char *
  195. circuit_list_path(origin_circuit_t *circ, int verbose)
  196. {
  197. return circuit_list_path_impl(circ, verbose, 0);
  198. }
  199. /** Allocate and return a comma-separated list of the currently built elements
  200. * of <b>circ</b>, giving each as a verbose nickname.
  201. */
  202. char *
  203. circuit_list_path_for_controller(origin_circuit_t *circ)
  204. {
  205. return circuit_list_path_impl(circ, 0, 1);
  206. }
  207. /** Log, at severity <b>severity</b>, the nicknames of each router in
  208. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  209. * exit point.
  210. */
  211. void
  212. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  213. {
  214. char *s = circuit_list_path(circ,1);
  215. tor_log(severity,domain,"%s",s);
  216. tor_free(s);
  217. }
  218. /** Tell the rep(utation)hist(ory) module about the status of the links
  219. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  220. * extended; the _first_ hop that isn't open (if any) is marked as
  221. * unable to extend.
  222. */
  223. /* XXXX Someday we should learn from OR circuits too. */
  224. void
  225. circuit_rep_hist_note_result(origin_circuit_t *circ)
  226. {
  227. crypt_path_t *hop;
  228. const char *prev_digest = NULL;
  229. hop = circ->cpath;
  230. if (!hop) /* circuit hasn't started building yet. */
  231. return;
  232. if (server_mode(get_options())) {
  233. const routerinfo_t *me = router_get_my_routerinfo();
  234. if (!me)
  235. return;
  236. prev_digest = me->cache_info.identity_digest;
  237. }
  238. do {
  239. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  240. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  241. if (prev_digest) {
  242. if (hop->state == CPATH_STATE_OPEN)
  243. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  244. else {
  245. rep_hist_note_extend_failed(prev_digest, node->identity);
  246. break;
  247. }
  248. }
  249. prev_digest = node->identity;
  250. } else {
  251. prev_digest = NULL;
  252. }
  253. hop=hop->next;
  254. } while (hop!=circ->cpath);
  255. }
  256. /** Pick all the entries in our cpath. Stop and return 0 when we're
  257. * happy, or return -1 if an error occurs. */
  258. static int
  259. onion_populate_cpath(origin_circuit_t *circ)
  260. {
  261. int r;
  262. again:
  263. r = onion_extend_cpath(circ);
  264. if (r < 0) {
  265. log_info(LD_CIRC,"Generating cpath hop failed.");
  266. return -1;
  267. }
  268. if (r == 0)
  269. goto again;
  270. return 0; /* if r == 1 */
  271. }
  272. /** Create and return a new origin circuit. Initialize its purpose and
  273. * build-state based on our arguments. The <b>flags</b> argument is a
  274. * bitfield of CIRCLAUNCH_* flags. */
  275. origin_circuit_t *
  276. origin_circuit_init(uint8_t purpose, int flags)
  277. {
  278. /* sets circ->p_circ_id and circ->p_chan */
  279. origin_circuit_t *circ = origin_circuit_new();
  280. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  281. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  282. circ->build_state->onehop_tunnel =
  283. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  284. circ->build_state->need_uptime =
  285. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  286. circ->build_state->need_capacity =
  287. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  288. circ->build_state->is_internal =
  289. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  290. circ->base_.purpose = purpose;
  291. return circ;
  292. }
  293. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  294. * is defined, then use that as your exit router, else choose a suitable
  295. * exit node.
  296. *
  297. * Also launch a connection to the first OR in the chosen path, if
  298. * it's not open already.
  299. */
  300. origin_circuit_t *
  301. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  302. {
  303. origin_circuit_t *circ;
  304. int err_reason = 0;
  305. circ = origin_circuit_init(purpose, flags);
  306. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  307. onion_populate_cpath(circ) < 0) {
  308. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  309. return NULL;
  310. }
  311. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  312. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  313. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  314. return NULL;
  315. }
  316. return circ;
  317. }
  318. /** Start establishing the first hop of our circuit. Figure out what
  319. * OR we should connect to, and if necessary start the connection to
  320. * it. If we're already connected, then send the 'create' cell.
  321. * Return 0 for ok, -reason if circ should be marked-for-close. */
  322. int
  323. circuit_handle_first_hop(origin_circuit_t *circ)
  324. {
  325. crypt_path_t *firsthop;
  326. channel_t *n_chan;
  327. int err_reason = 0;
  328. const char *msg = NULL;
  329. int should_launch = 0;
  330. firsthop = onion_next_hop_in_cpath(circ->cpath);
  331. tor_assert(firsthop);
  332. tor_assert(firsthop->extend_info);
  333. /* now see if we're already connected to the first OR in 'route' */
  334. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  335. fmt_addrport(&firsthop->extend_info->addr,
  336. firsthop->extend_info->port));
  337. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  338. &firsthop->extend_info->addr,
  339. &msg,
  340. &should_launch);
  341. if (!n_chan) {
  342. /* not currently connected in a useful way. */
  343. log_info(LD_CIRC, "Next router is %s: %s",
  344. safe_str_client(extend_info_describe(firsthop->extend_info)),
  345. msg?msg:"???");
  346. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  347. if (should_launch) {
  348. if (circ->build_state->onehop_tunnel)
  349. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  350. n_chan = channel_connect_for_circuit(
  351. &firsthop->extend_info->addr,
  352. firsthop->extend_info->port,
  353. firsthop->extend_info->identity_digest);
  354. if (!n_chan) { /* connect failed, forget the whole thing */
  355. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  356. return -END_CIRC_REASON_CONNECTFAILED;
  357. }
  358. }
  359. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  360. /* return success. The onion/circuit/etc will be taken care of
  361. * automatically (may already have been) whenever n_chan reaches
  362. * OR_CONN_STATE_OPEN.
  363. */
  364. return 0;
  365. } else { /* it's already open. use it. */
  366. tor_assert(!circ->base_.n_hop);
  367. circ->base_.n_chan = n_chan;
  368. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  369. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  370. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  371. return err_reason;
  372. }
  373. }
  374. return 0;
  375. }
  376. /** Find any circuits that are waiting on <b>or_conn</b> to become
  377. * open and get them to send their create cells forward.
  378. *
  379. * Status is 1 if connect succeeded, or 0 if connect failed.
  380. */
  381. void
  382. circuit_n_chan_done(channel_t *chan, int status)
  383. {
  384. smartlist_t *pending_circs;
  385. int err_reason = 0;
  386. tor_assert(chan);
  387. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  388. chan->nickname ? chan->nickname : "NULL",
  389. channel_get_canonical_remote_descr(chan), status);
  390. pending_circs = smartlist_new();
  391. circuit_get_all_pending_on_channel(pending_circs, chan);
  392. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  393. {
  394. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  395. * leaving them in in case it's possible for the status of a circuit to
  396. * change as we're going down the list. */
  397. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  398. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  399. continue;
  400. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  401. /* Look at addr/port. This is an unkeyed connection. */
  402. if (!channel_matches_extend_info(chan, circ->n_hop))
  403. continue;
  404. } else {
  405. /* We expected a key. See if it's the right one. */
  406. if (tor_memneq(chan->identity_digest,
  407. circ->n_hop->identity_digest, DIGEST_LEN))
  408. continue;
  409. }
  410. if (!status) { /* chan failed; close circ */
  411. log_info(LD_CIRC,"Channel failed; closing circ.");
  412. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  413. continue;
  414. }
  415. log_debug(LD_CIRC, "Found circ, sending create cell.");
  416. /* circuit_deliver_create_cell will set n_circ_id and add us to
  417. * chan_circuid_circuit_map, so we don't need to call
  418. * set_circid_chan here. */
  419. circ->n_chan = chan;
  420. extend_info_free(circ->n_hop);
  421. circ->n_hop = NULL;
  422. if (CIRCUIT_IS_ORIGIN(circ)) {
  423. if ((err_reason =
  424. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  425. log_info(LD_CIRC,
  426. "send_next_onion_skin failed; circuit marked for closing.");
  427. circuit_mark_for_close(circ, -err_reason);
  428. continue;
  429. /* XXX could this be bad, eg if next_onion_skin failed because conn
  430. * died? */
  431. }
  432. } else {
  433. /* pull the create cell out of circ->onionskin, and send it */
  434. tor_assert(circ->n_chan_onionskin);
  435. if (circuit_deliver_create_cell(circ,CELL_CREATE,
  436. circ->n_chan_onionskin)<0) {
  437. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  438. continue;
  439. }
  440. tor_free(circ->n_chan_onionskin);
  441. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  442. }
  443. }
  444. SMARTLIST_FOREACH_END(circ);
  445. smartlist_free(pending_circs);
  446. }
  447. /** Find a new circid that isn't currently in use on the circ->n_chan
  448. * for the outgoing
  449. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  450. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  451. * to this circuit.
  452. * Return -1 if we failed to find a suitable circid, else return 0.
  453. */
  454. static int
  455. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  456. const char *payload)
  457. {
  458. cell_t cell;
  459. circid_t id;
  460. tor_assert(circ);
  461. tor_assert(circ->n_chan);
  462. tor_assert(payload);
  463. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  464. id = get_unique_circ_id_by_chan(circ->n_chan);
  465. if (!id) {
  466. log_warn(LD_CIRC,"failed to get unique circID.");
  467. return -1;
  468. }
  469. log_debug(LD_CIRC,"Chosen circID %u.", id);
  470. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  471. memset(&cell, 0, sizeof(cell_t));
  472. cell.command = cell_type;
  473. cell.circ_id = circ->n_circ_id;
  474. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  475. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  476. CELL_DIRECTION_OUT, 0);
  477. if (CIRCUIT_IS_ORIGIN(circ)) {
  478. /* Update began timestamp for circuits starting their first hop */
  479. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  480. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  481. log_warn(LD_CIRC,
  482. "Got first hop for a circuit without an opened channel. "
  483. "State: %s.", channel_state_to_string(circ->n_chan->state));
  484. tor_fragile_assert();
  485. }
  486. tor_gettimeofday(&circ->timestamp_began);
  487. }
  488. /* mark it so it gets better rate limiting treatment. */
  489. channel_timestamp_client(circ->n_chan);
  490. }
  491. return 0;
  492. }
  493. /** We've decided to start our reachability testing. If all
  494. * is set, log this to the user. Return 1 if we did, or 0 if
  495. * we chose not to log anything. */
  496. int
  497. inform_testing_reachability(void)
  498. {
  499. char dirbuf[128];
  500. const routerinfo_t *me = router_get_my_routerinfo();
  501. if (!me)
  502. return 0;
  503. control_event_server_status(LOG_NOTICE,
  504. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  505. me->address, me->or_port);
  506. if (me->dir_port) {
  507. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  508. me->address, me->dir_port);
  509. control_event_server_status(LOG_NOTICE,
  510. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  511. me->address, me->dir_port);
  512. }
  513. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  514. "(this may take up to %d minutes -- look for log "
  515. "messages indicating success)",
  516. me->address, me->or_port,
  517. me->dir_port ? dirbuf : "",
  518. me->dir_port ? "are" : "is",
  519. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  520. return 1;
  521. }
  522. /** Return true iff we should send a create_fast cell to start building a given
  523. * circuit */
  524. static INLINE int
  525. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  526. {
  527. const or_options_t *options = get_options();
  528. tor_assert(circ->cpath);
  529. tor_assert(circ->cpath->extend_info);
  530. if (!circ->cpath->extend_info->onion_key)
  531. return 1; /* our hand is forced: only a create_fast will work. */
  532. if (!options->FastFirstHopPK)
  533. return 0; /* we prefer to avoid create_fast */
  534. if (public_server_mode(options)) {
  535. /* We're a server, and we know an onion key. We can choose.
  536. * Prefer to blend our circuit into the other circuits we are
  537. * creating on behalf of others. */
  538. return 0;
  539. }
  540. return 1;
  541. }
  542. /** Return true if <b>circ</b> is the type of circuit we want to count
  543. * timeouts from. In particular, we want it to have not completed yet
  544. * (already completing indicates we cannibalized it), and we want it to
  545. * have exactly three hops.
  546. */
  547. int
  548. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  549. {
  550. return !circ->has_opened
  551. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  552. }
  553. /** This is the backbone function for building circuits.
  554. *
  555. * If circ's first hop is closed, then we need to build a create
  556. * cell and send it forward.
  557. *
  558. * Otherwise, we need to build a relay extend cell and send it
  559. * forward.
  560. *
  561. * Return -reason if we want to tear down circ, else return 0.
  562. */
  563. int
  564. circuit_send_next_onion_skin(origin_circuit_t *circ)
  565. {
  566. crypt_path_t *hop;
  567. const node_t *node;
  568. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  569. char *onionskin;
  570. size_t payload_len;
  571. tor_assert(circ);
  572. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  573. int fast;
  574. uint8_t cell_type;
  575. log_debug(LD_CIRC,"First skin; sending create cell.");
  576. if (circ->build_state->onehop_tunnel)
  577. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  578. else
  579. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  580. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  581. fast = should_use_create_fast_for_circuit(circ);
  582. if (!fast) {
  583. /* We are an OR and we know the right onion key: we should
  584. * send an old slow create cell.
  585. */
  586. cell_type = CELL_CREATE;
  587. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  588. &(circ->cpath->dh_handshake_state),
  589. payload) < 0) {
  590. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  591. return - END_CIRC_REASON_INTERNAL;
  592. }
  593. note_request("cell: create", 1);
  594. } else {
  595. /* We are not an OR, and we're building the first hop of a circuit to a
  596. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  597. * and a DH operation. */
  598. cell_type = CELL_CREATE_FAST;
  599. memset(payload, 0, sizeof(payload));
  600. crypto_rand((char*) circ->cpath->fast_handshake_state,
  601. sizeof(circ->cpath->fast_handshake_state));
  602. memcpy(payload, circ->cpath->fast_handshake_state,
  603. sizeof(circ->cpath->fast_handshake_state));
  604. note_request("cell: create fast", 1);
  605. }
  606. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  607. return - END_CIRC_REASON_RESOURCELIMIT;
  608. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  609. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  610. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  611. fast ? "CREATE_FAST" : "CREATE",
  612. node ? node_describe(node) : "<unnamed>");
  613. } else {
  614. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  615. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  616. log_debug(LD_CIRC,"starting to send subsequent skin.");
  617. hop = onion_next_hop_in_cpath(circ->cpath);
  618. if (!hop) {
  619. /* done building the circuit. whew. */
  620. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  621. if (circuit_timeout_want_to_count_circ(circ)) {
  622. struct timeval end;
  623. long timediff;
  624. tor_gettimeofday(&end);
  625. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  626. /*
  627. * If the circuit build time is much greater than we would have cut
  628. * it off at, we probably had a suspend event along this codepath,
  629. * and we should discard the value.
  630. */
  631. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  632. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  633. "Assuming clock jump. Purpose %d (%s)", timediff,
  634. circ->base_.purpose,
  635. circuit_purpose_to_string(circ->base_.purpose));
  636. } else if (!circuit_build_times_disabled()) {
  637. /* Only count circuit times if the network is live */
  638. if (circuit_build_times_network_check_live(&circ_times)) {
  639. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  640. circuit_build_times_set_timeout(&circ_times);
  641. }
  642. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  643. circuit_build_times_network_circ_success(&circ_times);
  644. }
  645. }
  646. }
  647. log_info(LD_CIRC,"circuit built!");
  648. circuit_reset_failure_count(0);
  649. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  650. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  651. }
  652. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  653. const or_options_t *options = get_options();
  654. can_complete_circuit=1;
  655. /* FFFF Log a count of known routers here */
  656. log_notice(LD_GENERAL,
  657. "Tor has successfully opened a circuit. "
  658. "Looks like client functionality is working.");
  659. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  660. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  661. clear_broken_connection_map(1);
  662. if (server_mode(options) && !check_whether_orport_reachable()) {
  663. inform_testing_reachability();
  664. consider_testing_reachability(1, 1);
  665. }
  666. }
  667. pathbias_count_build_success(circ);
  668. circuit_rep_hist_note_result(circ);
  669. circuit_has_opened(circ); /* do other actions as necessary */
  670. /* We're done with measurement circuits here. Just close them */
  671. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  672. /* If a measurement circ ever gets back to us, consider it
  673. * succeeded for path bias */
  674. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  675. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  676. }
  677. return 0;
  678. }
  679. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  680. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  681. return - END_CIRC_REASON_INTERNAL;
  682. }
  683. set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
  684. set_uint16(payload+4, htons(hop->extend_info->port));
  685. onionskin = payload+2+4;
  686. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  687. hop->extend_info->identity_digest, DIGEST_LEN);
  688. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  689. if (onion_skin_create(hop->extend_info->onion_key,
  690. &(hop->dh_handshake_state), onionskin) < 0) {
  691. log_warn(LD_CIRC,"onion_skin_create failed.");
  692. return - END_CIRC_REASON_INTERNAL;
  693. }
  694. log_info(LD_CIRC,"Sending extend relay cell.");
  695. note_request("cell: extend", 1);
  696. /* send it to hop->prev, because it will transfer
  697. * it to a create cell and then send to hop */
  698. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  699. RELAY_COMMAND_EXTEND,
  700. payload, payload_len, hop->prev) < 0)
  701. return 0; /* circuit is closed */
  702. hop->state = CPATH_STATE_AWAITING_KEYS;
  703. }
  704. return 0;
  705. }
  706. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  707. * something has also gone wrong with our network: notify the user,
  708. * and abandon all not-yet-used circuits. */
  709. void
  710. circuit_note_clock_jumped(int seconds_elapsed)
  711. {
  712. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  713. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  714. "assuming established circuits no longer work.",
  715. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  716. seconds_elapsed >=0 ? "forward" : "backward");
  717. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  718. seconds_elapsed);
  719. can_complete_circuit=0; /* so it'll log when it works again */
  720. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  721. "CLOCK_JUMPED");
  722. circuit_mark_all_unused_circs();
  723. circuit_expire_all_dirty_circs();
  724. }
  725. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  726. * skin and identity digest for the next hop. If we're already connected,
  727. * pass the onion skin to the next hop using a create cell; otherwise
  728. * launch a new OR connection, and <b>circ</b> will notice when the
  729. * connection succeeds or fails.
  730. *
  731. * Return -1 if we want to warn and tear down the circuit, else return 0.
  732. */
  733. int
  734. circuit_extend(cell_t *cell, circuit_t *circ)
  735. {
  736. channel_t *n_chan;
  737. relay_header_t rh;
  738. char *onionskin;
  739. char *id_digest=NULL;
  740. uint32_t n_addr32;
  741. uint16_t n_port;
  742. tor_addr_t n_addr;
  743. const char *msg = NULL;
  744. int should_launch = 0;
  745. if (circ->n_chan) {
  746. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  747. "n_chan already set. Bug/attack. Closing.");
  748. return -1;
  749. }
  750. if (circ->n_hop) {
  751. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  752. "conn to next hop already launched. Bug/attack. Closing.");
  753. return -1;
  754. }
  755. if (!server_mode(get_options())) {
  756. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  757. "Got an extend cell, but running as a client. Closing.");
  758. return -1;
  759. }
  760. relay_header_unpack(&rh, cell->payload);
  761. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  762. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  763. "Wrong length %d on extend cell. Closing circuit.",
  764. rh.length);
  765. return -1;
  766. }
  767. n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  768. n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  769. onionskin = (char*) cell->payload+RELAY_HEADER_SIZE+4+2;
  770. id_digest = (char*) cell->payload+RELAY_HEADER_SIZE+4+2+
  771. ONIONSKIN_CHALLENGE_LEN;
  772. tor_addr_from_ipv4h(&n_addr, n_addr32);
  773. if (!n_port || !n_addr32) {
  774. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  775. "Client asked me to extend to zero destination port or addr.");
  776. return -1;
  777. }
  778. if (tor_addr_is_internal(&n_addr, 0) &&
  779. !get_options()->ExtendAllowPrivateAddresses) {
  780. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  781. "Client asked me to extend to a private address");
  782. return -1;
  783. }
  784. /* Check if they asked us for 0000..0000. We support using
  785. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  786. * but we don't want to let people send us extend cells for empty
  787. * fingerprints -- a) because it opens the user up to a mitm attack,
  788. * and b) because it lets an attacker force the relay to hold open a
  789. * new TLS connection for each extend request. */
  790. if (tor_digest_is_zero(id_digest)) {
  791. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  792. "Client asked me to extend without specifying an id_digest.");
  793. return -1;
  794. }
  795. /* Next, check if we're being asked to connect to the hop that the
  796. * extend cell came from. There isn't any reason for that, and it can
  797. * assist circular-path attacks. */
  798. if (tor_memeq(id_digest,
  799. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  800. DIGEST_LEN)) {
  801. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  802. "Client asked me to extend back to the previous hop.");
  803. return -1;
  804. }
  805. n_chan = channel_get_for_extend(id_digest,
  806. &n_addr,
  807. &msg,
  808. &should_launch);
  809. if (!n_chan) {
  810. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  811. fmt_addrport(&n_addr, n_port), msg?msg:"????");
  812. circ->n_hop = extend_info_new(NULL /*nickname*/,
  813. id_digest,
  814. NULL /*onion_key*/,
  815. &n_addr, n_port);
  816. circ->n_chan_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  817. memcpy(circ->n_chan_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  818. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  819. if (should_launch) {
  820. /* we should try to open a connection */
  821. n_chan = channel_connect_for_circuit(&n_addr, n_port, id_digest);
  822. if (!n_chan) {
  823. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  824. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  825. return 0;
  826. }
  827. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  828. }
  829. /* return success. The onion/circuit/etc will be taken care of
  830. * automatically (may already have been) whenever n_chan reaches
  831. * OR_CONN_STATE_OPEN.
  832. */
  833. return 0;
  834. }
  835. tor_assert(!circ->n_hop); /* Connection is already established. */
  836. circ->n_chan = n_chan;
  837. log_debug(LD_CIRC,
  838. "n_chan is %s",
  839. channel_get_canonical_remote_descr(n_chan));
  840. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  841. return -1;
  842. return 0;
  843. }
  844. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  845. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  846. * used as follows:
  847. * - 20 to initialize f_digest
  848. * - 20 to initialize b_digest
  849. * - 16 to key f_crypto
  850. * - 16 to key b_crypto
  851. *
  852. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  853. */
  854. int
  855. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  856. int reverse)
  857. {
  858. crypto_digest_t *tmp_digest;
  859. crypto_cipher_t *tmp_crypto;
  860. tor_assert(cpath);
  861. tor_assert(key_data);
  862. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  863. cpath->f_digest || cpath->b_digest));
  864. cpath->f_digest = crypto_digest_new();
  865. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  866. cpath->b_digest = crypto_digest_new();
  867. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  868. if (!(cpath->f_crypto =
  869. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  870. log_warn(LD_BUG,"Forward cipher initialization failed.");
  871. return -1;
  872. }
  873. if (!(cpath->b_crypto =
  874. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  875. log_warn(LD_BUG,"Backward cipher initialization failed.");
  876. return -1;
  877. }
  878. if (reverse) {
  879. tmp_digest = cpath->f_digest;
  880. cpath->f_digest = cpath->b_digest;
  881. cpath->b_digest = tmp_digest;
  882. tmp_crypto = cpath->f_crypto;
  883. cpath->f_crypto = cpath->b_crypto;
  884. cpath->b_crypto = tmp_crypto;
  885. }
  886. return 0;
  887. }
  888. /** The minimum number of circuit attempts before we start
  889. * thinking about warning about path bias and dropping guards */
  890. static int
  891. pathbias_get_min_circs(const or_options_t *options)
  892. {
  893. #define DFLT_PATH_BIAS_MIN_CIRC 150
  894. if (options->PathBiasCircThreshold >= 5)
  895. return options->PathBiasCircThreshold;
  896. else
  897. return networkstatus_get_param(NULL, "pb_mincircs",
  898. DFLT_PATH_BIAS_MIN_CIRC,
  899. 5, INT32_MAX);
  900. }
  901. /** The circuit success rate below which we issue a notice */
  902. static double
  903. pathbias_get_notice_rate(const or_options_t *options)
  904. {
  905. #define DFLT_PATH_BIAS_NOTICE_PCT 70
  906. if (options->PathBiasNoticeRate >= 0.0)
  907. return options->PathBiasNoticeRate;
  908. else
  909. return networkstatus_get_param(NULL, "pb_noticepct",
  910. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  911. }
  912. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  913. /** The circuit success rate below which we issue a warn */
  914. double
  915. pathbias_get_warn_rate(const or_options_t *options)
  916. {
  917. #define DFLT_PATH_BIAS_WARN_PCT 50
  918. if (options->PathBiasWarnRate >= 0.0)
  919. return options->PathBiasWarnRate;
  920. else
  921. return networkstatus_get_param(NULL, "pb_warnpct",
  922. DFLT_PATH_BIAS_WARN_PCT, 0, 100)/100.0;
  923. }
  924. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  925. /**
  926. * The extreme rate is the rate at which we would drop the guard,
  927. * if pb_dropguard is also set. Otherwise we just warn.
  928. */
  929. double
  930. pathbias_get_extreme_rate(const or_options_t *options)
  931. {
  932. #define DFLT_PATH_BIAS_EXTREME_PCT 30
  933. if (options->PathBiasExtremeRate >= 0.0)
  934. return options->PathBiasExtremeRate;
  935. else
  936. return networkstatus_get_param(NULL, "pb_extremepct",
  937. DFLT_PATH_BIAS_EXTREME_PCT, 0, 100)/100.0;
  938. }
  939. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  940. /**
  941. * If 1, we actually disable use of guards that fall below
  942. * the extreme_pct.
  943. */
  944. int
  945. pathbias_get_dropguards(const or_options_t *options)
  946. {
  947. #define DFLT_PATH_BIAS_DROP_GUARDS 0
  948. if (options->PathBiasDropGuards >= 0)
  949. return options->PathBiasDropGuards;
  950. else
  951. return networkstatus_get_param(NULL, "pb_dropguards",
  952. DFLT_PATH_BIAS_DROP_GUARDS, 0, 100)/100.0;
  953. }
  954. /**
  955. * This is the number of circuits at which we scale our
  956. * counts by mult_factor/scale_factor. Note, this count is
  957. * not exact, as we only perform the scaling in the event
  958. * of no integer truncation.
  959. */
  960. static int
  961. pathbias_get_scale_threshold(const or_options_t *options)
  962. {
  963. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
  964. if (options->PathBiasScaleThreshold >= 10)
  965. return options->PathBiasScaleThreshold;
  966. else
  967. return networkstatus_get_param(NULL, "pb_scalecircs",
  968. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  969. INT32_MAX);
  970. }
  971. /**
  972. * The scale factor is the denominator for our scaling
  973. * of circuit counts for our path bias window. Note that
  974. * we must be careful of the values we use here, as the
  975. * code only scales in the event of no integer truncation.
  976. */
  977. static int
  978. pathbias_get_scale_factor(const or_options_t *options)
  979. {
  980. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  981. if (options->PathBiasScaleFactor >= 1)
  982. return options->PathBiasScaleFactor;
  983. else
  984. return networkstatus_get_param(NULL, "pb_scalefactor",
  985. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  986. }
  987. /**
  988. * The mult factor is the numerator for our scaling
  989. * of circuit counts for our path bias window. It
  990. * allows us to scale by fractions.
  991. */
  992. static int
  993. pathbias_get_mult_factor(const or_options_t *options)
  994. {
  995. #define DFLT_PATH_BIAS_MULT_FACTOR 1
  996. if (options->PathBiasMultFactor >= 1)
  997. return options->PathBiasMultFactor;
  998. else
  999. return networkstatus_get_param(NULL, "pb_multfactor",
  1000. DFLT_PATH_BIAS_MULT_FACTOR, 1,
  1001. pathbias_get_scale_factor(options));
  1002. }
  1003. /**
  1004. * If this parameter is set to a true value (default), we use the
  1005. * successful_circuits_closed. Otherwise, we use the success_count.
  1006. */
  1007. static int
  1008. pathbias_use_close_counts(const or_options_t *options)
  1009. {
  1010. #define DFLT_PATH_BIAS_USE_CLOSE_COUNTS 1
  1011. if (options->PathBiasUseCloseCounts >= 0)
  1012. return options->PathBiasUseCloseCounts;
  1013. else
  1014. return networkstatus_get_param(NULL, "pb_useclosecounts",
  1015. DFLT_PATH_BIAS_USE_CLOSE_COUNTS, 0, 1);
  1016. }
  1017. /**
  1018. * Convert a Guard's path state to string.
  1019. */
  1020. static const char *
  1021. pathbias_state_to_string(path_state_t state)
  1022. {
  1023. switch (state) {
  1024. case PATH_STATE_NEW_CIRC:
  1025. return "new";
  1026. case PATH_STATE_BUILD_ATTEMPTED:
  1027. return "build attempted";
  1028. case PATH_STATE_BUILD_SUCCEEDED:
  1029. return "build succeeded";
  1030. case PATH_STATE_USE_SUCCEEDED:
  1031. return "use succeeded";
  1032. }
  1033. return "unknown";
  1034. }
  1035. /**
  1036. * This function decides if a circuit has progressed far enough to count
  1037. * as a circuit "attempt". As long as end-to-end tagging is possible,
  1038. * we assume the adversary will use it over hop-to-hop failure. Therefore,
  1039. * we only need to account bias for the last hop. This should make us
  1040. * much more resilient to ambient circuit failure, and also make that
  1041. * failure easier to measure (we only need to measure Exit failure rates).
  1042. */
  1043. static int
  1044. pathbias_is_new_circ_attempt(origin_circuit_t *circ)
  1045. {
  1046. #define N2N_TAGGING_IS_POSSIBLE
  1047. #ifdef N2N_TAGGING_IS_POSSIBLE
  1048. /* cpath is a circular list. We want circs with more than one hop,
  1049. * and the second hop must be waiting for keys still (it's just
  1050. * about to get them). */
  1051. return circ->cpath->next != circ->cpath &&
  1052. circ->cpath->next->state == CPATH_STATE_AWAITING_KEYS;
  1053. #else
  1054. /* If tagging attacks are no longer possible, we probably want to
  1055. * count bias from the first hop. However, one could argue that
  1056. * timing-based tagging is still more useful than per-hop failure.
  1057. * In which case, we'd never want to use this.
  1058. */
  1059. return circ->cpath->state == CPATH_STATE_AWAITING_KEYS;
  1060. #endif
  1061. }
  1062. /**
  1063. * Decide if the path bias code should count a circuit.
  1064. *
  1065. * @returns 1 if we should count it, 0 otherwise.
  1066. */
  1067. static int
  1068. pathbias_should_count(origin_circuit_t *circ)
  1069. {
  1070. #define PATHBIAS_COUNT_INTERVAL (600)
  1071. static ratelim_t count_limit =
  1072. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  1073. char *rate_msg = NULL;
  1074. /* We can't do path bias accounting without entry guards.
  1075. * Testing and controller circuits also have no guards.
  1076. *
  1077. * We also don't count server-side rends, because their
  1078. * endpoint could be chosen maliciously.
  1079. * Similarly, we can't count client-side intro attempts,
  1080. * because clients can be manipulated into connecting to
  1081. * malicious intro points. */
  1082. if (get_options()->UseEntryGuards == 0 ||
  1083. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1084. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  1085. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1086. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  1087. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1088. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  1089. return 0;
  1090. }
  1091. /* Completely ignore one hop circuits */
  1092. if (circ->build_state->onehop_tunnel ||
  1093. circ->build_state->desired_path_len == 1) {
  1094. /* Check for inconsistency */
  1095. if (circ->build_state->desired_path_len != 1 ||
  1096. !circ->build_state->onehop_tunnel) {
  1097. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  1098. log_notice(LD_BUG,
  1099. "One-hop circuit has length %d. Path state is %s. "
  1100. "Circuit is a %s currently %s.%s",
  1101. circ->build_state->desired_path_len,
  1102. pathbias_state_to_string(circ->path_state),
  1103. circuit_purpose_to_string(circ->base_.purpose),
  1104. circuit_state_to_string(circ->base_.state),
  1105. rate_msg);
  1106. tor_free(rate_msg);
  1107. }
  1108. tor_fragile_assert();
  1109. }
  1110. return 0;
  1111. }
  1112. return 1;
  1113. }
  1114. /**
  1115. * Check our circuit state to see if this is a successful circuit attempt.
  1116. * If so, record it in the current guard's path bias circ_attempt count.
  1117. *
  1118. * Also check for several potential error cases for bug #6475.
  1119. */
  1120. static int
  1121. pathbias_count_circ_attempt(origin_circuit_t *circ)
  1122. {
  1123. #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
  1124. static ratelim_t circ_attempt_notice_limit =
  1125. RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL);
  1126. char *rate_msg = NULL;
  1127. if (!pathbias_should_count(circ)) {
  1128. return 0;
  1129. }
  1130. if (pathbias_is_new_circ_attempt(circ)) {
  1131. /* Help track down the real cause of bug #6475: */
  1132. if (circ->has_opened && circ->path_state != PATH_STATE_BUILD_ATTEMPTED) {
  1133. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1134. approx_time()))) {
  1135. log_info(LD_BUG,
  1136. "Opened circuit is in strange path state %s. "
  1137. "Circuit is a %s currently %s.%s",
  1138. pathbias_state_to_string(circ->path_state),
  1139. circuit_purpose_to_string(circ->base_.purpose),
  1140. circuit_state_to_string(circ->base_.state),
  1141. rate_msg);
  1142. tor_free(rate_msg);
  1143. }
  1144. }
  1145. /* Don't re-count cannibalized circs.. */
  1146. if (!circ->has_opened) {
  1147. entry_guard_t *guard = NULL;
  1148. if (circ->cpath && circ->cpath->extend_info) {
  1149. guard = entry_guard_get_by_id_digest(
  1150. circ->cpath->extend_info->identity_digest);
  1151. } else if (circ->base_.n_chan) {
  1152. guard =
  1153. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1154. }
  1155. if (guard) {
  1156. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1157. circ->path_state = PATH_STATE_BUILD_ATTEMPTED;
  1158. if (entry_guard_inc_circ_attempt_count(guard) < 0) {
  1159. /* Bogus guard; we already warned. */
  1160. return -END_CIRC_REASON_TORPROTOCOL;
  1161. }
  1162. } else {
  1163. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1164. approx_time()))) {
  1165. log_info(LD_BUG,
  1166. "Unopened circuit has strange path state %s. "
  1167. "Circuit is a %s currently %s.%s",
  1168. pathbias_state_to_string(circ->path_state),
  1169. circuit_purpose_to_string(circ->base_.purpose),
  1170. circuit_state_to_string(circ->base_.state),
  1171. rate_msg);
  1172. tor_free(rate_msg);
  1173. }
  1174. }
  1175. } else {
  1176. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1177. approx_time()))) {
  1178. log_info(LD_BUG,
  1179. "Unopened circuit has no known guard. "
  1180. "Circuit is a %s currently %s.%s",
  1181. circuit_purpose_to_string(circ->base_.purpose),
  1182. circuit_state_to_string(circ->base_.state),
  1183. rate_msg);
  1184. tor_free(rate_msg);
  1185. }
  1186. }
  1187. }
  1188. } else {
  1189. /* Help track down the real cause of bug #6475: */
  1190. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1191. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  1192. approx_time()))) {
  1193. log_info(LD_BUG,
  1194. "A %s circuit is in cpath state %d (opened: %d). "
  1195. "Circuit is a %s currently %s.%s",
  1196. pathbias_state_to_string(circ->path_state),
  1197. circ->cpath->state, circ->has_opened,
  1198. circuit_purpose_to_string(circ->base_.purpose),
  1199. circuit_state_to_string(circ->base_.state),
  1200. rate_msg);
  1201. tor_free(rate_msg);
  1202. }
  1203. }
  1204. }
  1205. return 0;
  1206. }
  1207. /**
  1208. * Check our circuit state to see if this is a successful circuit
  1209. * completion. If so, record it in the current guard's path bias
  1210. * success count.
  1211. *
  1212. * Also check for several potential error cases for bug #6475.
  1213. */
  1214. static void
  1215. pathbias_count_build_success(origin_circuit_t *circ)
  1216. {
  1217. #define SUCCESS_NOTICE_INTERVAL (600)
  1218. static ratelim_t success_notice_limit =
  1219. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1220. char *rate_msg = NULL;
  1221. entry_guard_t *guard = NULL;
  1222. if (!pathbias_should_count(circ)) {
  1223. return;
  1224. }
  1225. /* Don't count cannibalized/reused circs for path bias
  1226. * build success.. They get counted under use success */
  1227. if (!circ->has_opened) {
  1228. if (circ->cpath && circ->cpath->extend_info) {
  1229. guard = entry_guard_get_by_id_digest(
  1230. circ->cpath->extend_info->identity_digest);
  1231. }
  1232. if (guard) {
  1233. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  1234. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  1235. guard->circ_successes++;
  1236. log_info(LD_CIRC, "Got success count %lf/%lf for guard %s=%s",
  1237. guard->circ_successes, guard->circ_attempts,
  1238. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1239. } else {
  1240. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1241. approx_time()))) {
  1242. log_info(LD_BUG,
  1243. "Succeeded circuit is in strange path state %s. "
  1244. "Circuit is a %s currently %s.%s",
  1245. pathbias_state_to_string(circ->path_state),
  1246. circuit_purpose_to_string(circ->base_.purpose),
  1247. circuit_state_to_string(circ->base_.state),
  1248. rate_msg);
  1249. tor_free(rate_msg);
  1250. }
  1251. }
  1252. if (guard->circ_attempts < guard->circ_successes) {
  1253. log_notice(LD_BUG, "Unexpectedly high successes counts (%lf/%lf) "
  1254. "for guard %s=%s",
  1255. guard->circ_successes, guard->circ_attempts,
  1256. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1257. }
  1258. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1259. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1260. * No need to log that case. */
  1261. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1262. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1263. approx_time()))) {
  1264. log_info(LD_BUG,
  1265. "Completed circuit has no known guard. "
  1266. "Circuit is a %s currently %s.%s",
  1267. circuit_purpose_to_string(circ->base_.purpose),
  1268. circuit_state_to_string(circ->base_.state),
  1269. rate_msg);
  1270. tor_free(rate_msg);
  1271. }
  1272. }
  1273. } else {
  1274. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1275. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1276. approx_time()))) {
  1277. log_info(LD_BUG,
  1278. "Opened circuit is in strange path state %s. "
  1279. "Circuit is a %s currently %s.%s",
  1280. pathbias_state_to_string(circ->path_state),
  1281. circuit_purpose_to_string(circ->base_.purpose),
  1282. circuit_state_to_string(circ->base_.state),
  1283. rate_msg);
  1284. tor_free(rate_msg);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. /**
  1290. * Check if a circuit was used and/or closed successfully.
  1291. */
  1292. void
  1293. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  1294. {
  1295. circuit_t *circ = &ocirc->base_;
  1296. if (!pathbias_should_count(ocirc)) {
  1297. return;
  1298. }
  1299. if (ocirc->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1300. if (circ->timestamp_dirty) {
  1301. /* Any circuit where there were attempted streams but no successful
  1302. * streams could be bias */
  1303. // XXX: May open up attacks if the adversary can force connections
  1304. // on unresponsive hosts to use new circs. Vidalia displayes a "Retrying"
  1305. // state.. Can we use that? Does optimistic data change this?
  1306. log_info(LD_CIRC,
  1307. "Circuit %d closed without successful use for reason %d. "
  1308. "Circuit purpose %d currently %s.",
  1309. ocirc->global_identifier,
  1310. reason, circ->purpose, circuit_state_to_string(circ->state));
  1311. pathbias_count_unusable(ocirc);
  1312. } else {
  1313. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  1314. /* Unused remote circ close reasons all could be bias */
  1315. log_info(LD_CIRC,
  1316. "Circuit %d remote-closed without successful use for reason %d. "
  1317. "Circuit purpose %d currently %s.",
  1318. ocirc->global_identifier,
  1319. reason, circ->purpose, circuit_state_to_string(circ->state));
  1320. pathbias_count_collapse(ocirc);
  1321. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  1322. == END_CIRC_REASON_CHANNEL_CLOSED &&
  1323. circ->n_chan &&
  1324. circ->n_chan->reason_for_closing
  1325. != CHANNEL_CLOSE_REQUESTED) {
  1326. /* If we didn't close the channel ourselves, it could be bias */
  1327. /* FIXME: Only count bias if the network is live?
  1328. * What about clock jumps/suspends? */
  1329. log_info(LD_CIRC,
  1330. "Circuit %d's channel closed without successful use for reason "
  1331. "%d, channel reason %d. Circuit purpose %d currently %s.",
  1332. ocirc->global_identifier,
  1333. reason, circ->n_chan->reason_for_closing,
  1334. circ->purpose, circuit_state_to_string(circ->state));
  1335. pathbias_count_collapse(ocirc);
  1336. } else {
  1337. pathbias_count_successful_close(ocirc);
  1338. }
  1339. }
  1340. } else if (ocirc->path_state == PATH_STATE_USE_SUCCEEDED) {
  1341. pathbias_count_successful_close(ocirc);
  1342. }
  1343. }
  1344. /**
  1345. * Count a successfully closed circuit.
  1346. */
  1347. static void
  1348. pathbias_count_successful_close(origin_circuit_t *circ)
  1349. {
  1350. entry_guard_t *guard = NULL;
  1351. if (!pathbias_should_count(circ)) {
  1352. return;
  1353. }
  1354. if (circ->cpath && circ->cpath->extend_info) {
  1355. guard = entry_guard_get_by_id_digest(
  1356. circ->cpath->extend_info->identity_digest);
  1357. }
  1358. if (guard) {
  1359. /* In the long run: circuit_success ~= successful_circuit_close +
  1360. * circ_failure + stream_failure */
  1361. guard->successful_circuits_closed++;
  1362. entry_guards_changed();
  1363. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1364. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1365. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1366. * No need to log that case. */
  1367. log_info(LD_BUG,
  1368. "Successfully closed circuit has no known guard. "
  1369. "Circuit is a %s currently %s",
  1370. circuit_purpose_to_string(circ->base_.purpose),
  1371. circuit_state_to_string(circ->base_.state));
  1372. }
  1373. }
  1374. /**
  1375. * Count a circuit that fails after it is built, but before it can
  1376. * carry any traffic.
  1377. *
  1378. * This is needed because there are ways to destroy a
  1379. * circuit after it has successfully completed. Right now, this is
  1380. * used for purely informational/debugging purposes.
  1381. */
  1382. static void
  1383. pathbias_count_collapse(origin_circuit_t *circ)
  1384. {
  1385. entry_guard_t *guard = NULL;
  1386. if (!pathbias_should_count(circ)) {
  1387. return;
  1388. }
  1389. if (circ->cpath && circ->cpath->extend_info) {
  1390. guard = entry_guard_get_by_id_digest(
  1391. circ->cpath->extend_info->identity_digest);
  1392. }
  1393. if (guard) {
  1394. guard->collapsed_circuits++;
  1395. entry_guards_changed();
  1396. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1397. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1398. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1399. * No need to log that case. */
  1400. log_info(LD_BUG,
  1401. "Destroyed circuit has no known guard. "
  1402. "Circuit is a %s currently %s",
  1403. circuit_purpose_to_string(circ->base_.purpose),
  1404. circuit_state_to_string(circ->base_.state));
  1405. }
  1406. }
  1407. static void
  1408. pathbias_count_unusable(origin_circuit_t *circ)
  1409. {
  1410. entry_guard_t *guard = NULL;
  1411. if (!pathbias_should_count(circ)) {
  1412. return;
  1413. }
  1414. if (circ->cpath && circ->cpath->extend_info) {
  1415. guard = entry_guard_get_by_id_digest(
  1416. circ->cpath->extend_info->identity_digest);
  1417. }
  1418. if (guard) {
  1419. guard->unusable_circuits++;
  1420. entry_guards_changed();
  1421. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1422. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1423. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1424. * No need to log that case. */
  1425. log_info(LD_BUG,
  1426. "Stream-failing circuit has no known guard. "
  1427. "Circuit is a %s currently %s",
  1428. circuit_purpose_to_string(circ->base_.purpose),
  1429. circuit_state_to_string(circ->base_.state));
  1430. }
  1431. }
  1432. /**
  1433. * Count timeouts for path bias log messages.
  1434. *
  1435. * These counts are purely informational.
  1436. */
  1437. void
  1438. pathbias_count_timeout(origin_circuit_t *circ)
  1439. {
  1440. entry_guard_t *guard = NULL;
  1441. if (!pathbias_should_count(circ)) {
  1442. return;
  1443. }
  1444. /* For hidden service circs, they can actually be used
  1445. * successfully and then time out later (because
  1446. * the other side declines to use them). */
  1447. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1448. return;
  1449. }
  1450. if (circ->cpath && circ->cpath->extend_info) {
  1451. guard = entry_guard_get_by_id_digest(
  1452. circ->cpath->extend_info->identity_digest);
  1453. }
  1454. if (guard) {
  1455. guard->timeouts++;
  1456. entry_guards_changed();
  1457. }
  1458. }
  1459. // XXX: DOCDOC
  1460. double
  1461. pathbias_get_closed_count(entry_guard_t *guard)
  1462. {
  1463. circuit_t *circ = global_circuitlist;
  1464. int open_circuits = 0;
  1465. /* Count currently open circuits. Give them the benefit of the doubt */
  1466. for ( ; circ; circ = circ->next) {
  1467. origin_circuit_t *ocirc = NULL;
  1468. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1469. circ->marked_for_close) /* already counted */
  1470. continue;
  1471. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1472. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1473. continue;
  1474. if (ocirc->path_state >= PATH_STATE_BUILD_SUCCEEDED &&
  1475. (memcmp(guard->identity,
  1476. ocirc->cpath->extend_info->identity_digest,
  1477. DIGEST_LEN)
  1478. == 0)) {
  1479. open_circuits++;
  1480. }
  1481. }
  1482. return guard->successful_circuits_closed + open_circuits;
  1483. }
  1484. /**
  1485. * This function checks the consensus parameters to decide
  1486. * if it should return guard->circ_successes or
  1487. * guard->successful_circuits_closed.
  1488. */
  1489. double
  1490. pathbias_get_success_count(entry_guard_t *guard)
  1491. {
  1492. if (pathbias_use_close_counts(get_options())) {
  1493. return pathbias_get_closed_count(guard);
  1494. } else {
  1495. return guard->circ_successes;
  1496. }
  1497. }
  1498. /** Increment the number of times we successfully extended a circuit to
  1499. * 'guard', first checking if the failure rate is high enough that we should
  1500. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  1501. * guard looks fine. */
  1502. static int
  1503. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  1504. {
  1505. const or_options_t *options = get_options();
  1506. entry_guards_changed();
  1507. if (guard->circ_attempts > pathbias_get_min_circs(options)) {
  1508. /* Note: We rely on the < comparison here to allow us to set a 0
  1509. * rate and disable the feature entirely. If refactoring, don't
  1510. * change to <= */
  1511. if (pathbias_get_success_count(guard)/guard->circ_attempts
  1512. < pathbias_get_extreme_rate(options)) {
  1513. /* Dropping is currently disabled by default. */
  1514. if (pathbias_get_dropguards(options)) {
  1515. if (!guard->path_bias_disabled) {
  1516. log_warn(LD_CIRC,
  1517. "Your Guard %s=%s is failing an extremely large amount of "
  1518. "circuits. To avoid potential route manipluation attacks, "
  1519. "Tor has disabled use of this guard. "
  1520. "Success counts are %d/%d. %d circuits completed, %d "
  1521. "were unusable, %d collapsed, and %d timed out. For "
  1522. "reference, your timeout cutoff is %ld seconds.",
  1523. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1524. (int)pathbias_get_closed_count(guard),
  1525. (int)guard->circ_attempts, (int)guard->circ_successes,
  1526. (int)guard->unusable_circuits,
  1527. (int)guard->collapsed_circuits, (int)guard->timeouts,
  1528. (long)circ_times.close_ms/1000);
  1529. guard->path_bias_disabled = 1;
  1530. guard->bad_since = approx_time();
  1531. return -1;
  1532. }
  1533. } else if (!guard->path_bias_extreme) {
  1534. guard->path_bias_extreme = 1;
  1535. log_warn(LD_CIRC,
  1536. "Your Guard %s=%s is failing an extremely large amount of "
  1537. "circuits. This could indicate a route manipulation attack, "
  1538. "extreme network overload, or a bug. "
  1539. "Success counts are %d/%d. %d circuits completed, %d "
  1540. "were unusable, %d collapsed, and %d timed out. For "
  1541. "reference, your timeout cutoff is %ld seconds.",
  1542. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1543. (int)pathbias_get_closed_count(guard),
  1544. (int)guard->circ_attempts, (int)guard->circ_successes,
  1545. (int)guard->unusable_circuits,
  1546. (int)guard->collapsed_circuits, (int)guard->timeouts,
  1547. (long)circ_times.close_ms/1000);
  1548. }
  1549. } else if (pathbias_get_success_count(guard)/((double)guard->circ_attempts)
  1550. < pathbias_get_warn_rate(options)) {
  1551. if (!guard->path_bias_warned) {
  1552. guard->path_bias_warned = 1;
  1553. log_warn(LD_CIRC,
  1554. "Your Guard %s=%s is failing a very large amount of "
  1555. "circuits. Most likely this means the Tor network is "
  1556. "overloaded, but it could also mean an attack against "
  1557. "you or the potentially the guard itself. "
  1558. "Success counts are %d/%d. %d circuits completed, %d "
  1559. "were unusable, %d collapsed, and %d timed out. For "
  1560. "reference, your timeout cutoff is %ld seconds.",
  1561. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1562. (int)pathbias_get_closed_count(guard),
  1563. (int)guard->circ_attempts, (int)guard->circ_successes,
  1564. (int)guard->unusable_circuits,
  1565. (int)guard->collapsed_circuits, (int)guard->timeouts,
  1566. (long)circ_times.close_ms/1000);
  1567. }
  1568. } else if (pathbias_get_success_count(guard)/((double)guard->circ_attempts)
  1569. < pathbias_get_notice_rate(options)) {
  1570. if (!guard->path_bias_noticed) {
  1571. guard->path_bias_noticed = 1;
  1572. log_notice(LD_CIRC,
  1573. "Your Guard %s=%s is failing more circuits than usual. "
  1574. "Most likely this means the Tor network is overloaded. "
  1575. "Success counts are %d/%d. %d circuits completed, %d "
  1576. "were unusable, %d collapsed, and %d timed out. For "
  1577. "reference, your timeout cutoff is %ld seconds.",
  1578. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1579. (int)pathbias_get_closed_count(guard),
  1580. (int)guard->circ_attempts, (int)guard->circ_successes,
  1581. (int)guard->unusable_circuits,
  1582. (int)guard->collapsed_circuits, (int)guard->timeouts,
  1583. (long)circ_times.close_ms/1000);
  1584. }
  1585. }
  1586. }
  1587. /* If we get a ton of circuits, just scale everything down */
  1588. if (guard->circ_attempts > pathbias_get_scale_threshold(options)) {
  1589. const int scale_factor = pathbias_get_scale_factor(options);
  1590. const int mult_factor = pathbias_get_mult_factor(options);
  1591. log_info(LD_CIRC,
  1592. "Scaling pathbias counts to (%lf/%lf)*(%d/%d) for guard %s=%s",
  1593. guard->circ_successes, guard->circ_attempts,
  1594. mult_factor, scale_factor, guard->nickname,
  1595. hex_str(guard->identity, DIGEST_LEN));
  1596. guard->circ_attempts *= mult_factor;
  1597. guard->circ_successes *= mult_factor;
  1598. guard->timeouts *= mult_factor;
  1599. guard->successful_circuits_closed *= mult_factor;
  1600. guard->collapsed_circuits *= mult_factor;
  1601. guard->unusable_circuits *= mult_factor;
  1602. guard->circ_attempts /= scale_factor;
  1603. guard->circ_successes /= scale_factor;
  1604. guard->timeouts /= scale_factor;
  1605. guard->successful_circuits_closed /= scale_factor;
  1606. guard->collapsed_circuits /= scale_factor;
  1607. guard->unusable_circuits /= scale_factor;
  1608. }
  1609. guard->circ_attempts++;
  1610. log_info(LD_CIRC, "Got success count %lf/%lf for guard %s=%s",
  1611. guard->circ_successes, guard->circ_attempts, guard->nickname,
  1612. hex_str(guard->identity, DIGEST_LEN));
  1613. return 0;
  1614. }
  1615. /** A created or extended cell came back to us on the circuit, and it included
  1616. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  1617. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  1618. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  1619. *
  1620. * Calculate the appropriate keys and digests, make sure KH is
  1621. * correct, and initialize this hop of the cpath.
  1622. *
  1623. * Return - reason if we want to mark circ for close, else return 0.
  1624. */
  1625. int
  1626. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  1627. const uint8_t *reply)
  1628. {
  1629. char keys[CPATH_KEY_MATERIAL_LEN];
  1630. crypt_path_t *hop;
  1631. int rv;
  1632. if ((rv = pathbias_count_circ_attempt(circ)) < 0)
  1633. return rv;
  1634. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1635. hop = circ->cpath;
  1636. } else {
  1637. hop = onion_next_hop_in_cpath(circ->cpath);
  1638. if (!hop) { /* got an extended when we're all done? */
  1639. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1640. return - END_CIRC_REASON_TORPROTOCOL;
  1641. }
  1642. }
  1643. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1644. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  1645. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  1646. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1647. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1648. return -END_CIRC_REASON_TORPROTOCOL;
  1649. }
  1650. /* Remember hash of g^xy */
  1651. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  1652. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  1653. if (fast_client_handshake(hop->fast_handshake_state, reply,
  1654. (uint8_t*)keys,
  1655. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1656. log_warn(LD_CIRC,"fast_client_handshake failed.");
  1657. return -END_CIRC_REASON_TORPROTOCOL;
  1658. }
  1659. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  1660. } else {
  1661. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  1662. return -END_CIRC_REASON_TORPROTOCOL;
  1663. }
  1664. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  1665. hop->dh_handshake_state = NULL;
  1666. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  1667. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1668. return -END_CIRC_REASON_TORPROTOCOL;
  1669. }
  1670. hop->state = CPATH_STATE_OPEN;
  1671. log_info(LD_CIRC,"Finished building %scircuit hop:",
  1672. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  1673. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1674. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1675. return 0;
  1676. }
  1677. /** We received a relay truncated cell on circ.
  1678. *
  1679. * Since we don't ask for truncates currently, getting a truncated
  1680. * means that a connection broke or an extend failed. For now,
  1681. * just give up: for circ to close, and return 0.
  1682. */
  1683. int
  1684. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1685. {
  1686. // crypt_path_t *victim;
  1687. // connection_t *stream;
  1688. tor_assert(circ);
  1689. tor_assert(layer);
  1690. /* XXX Since we don't ask for truncates currently, getting a truncated
  1691. * means that a connection broke or an extend failed. For now,
  1692. * just give up.
  1693. */
  1694. circuit_mark_for_close(TO_CIRCUIT(circ),
  1695. END_CIRC_REASON_FLAG_REMOTE|reason);
  1696. return 0;
  1697. #if 0
  1698. while (layer->next != circ->cpath) {
  1699. /* we need to clear out layer->next */
  1700. victim = layer->next;
  1701. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1702. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1703. if (stream->cpath_layer == victim) {
  1704. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1705. stream->stream_id);
  1706. /* no need to send 'end' relay cells,
  1707. * because the other side's already dead
  1708. */
  1709. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1710. }
  1711. }
  1712. layer->next = victim->next;
  1713. circuit_free_cpath_node(victim);
  1714. }
  1715. log_info(LD_CIRC, "finished");
  1716. return 0;
  1717. #endif
  1718. }
  1719. /** Given a response payload and keys, initialize, then send a created
  1720. * cell back.
  1721. */
  1722. int
  1723. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  1724. const char *keys)
  1725. {
  1726. cell_t cell;
  1727. crypt_path_t *tmp_cpath;
  1728. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1729. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1730. memset(&cell, 0, sizeof(cell_t));
  1731. cell.command = cell_type;
  1732. cell.circ_id = circ->p_circ_id;
  1733. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1734. memcpy(cell.payload, payload,
  1735. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  1736. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1737. (unsigned int)get_uint32(keys),
  1738. (unsigned int)get_uint32(keys+20));
  1739. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1740. log_warn(LD_BUG,"Circuit initialization failed");
  1741. tor_free(tmp_cpath);
  1742. return -1;
  1743. }
  1744. circ->n_digest = tmp_cpath->f_digest;
  1745. circ->n_crypto = tmp_cpath->f_crypto;
  1746. circ->p_digest = tmp_cpath->b_digest;
  1747. circ->p_crypto = tmp_cpath->b_crypto;
  1748. tmp_cpath->magic = 0;
  1749. tor_free(tmp_cpath);
  1750. if (cell_type == CELL_CREATED)
  1751. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  1752. else
  1753. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  1754. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  1755. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1756. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1757. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1758. circ->is_first_hop ? "created_fast" : "created");
  1759. if (!channel_is_local(circ->p_chan) &&
  1760. !channel_is_outgoing(circ->p_chan)) {
  1761. /* record that we could process create cells from a non-local conn
  1762. * that we didn't initiate; presumably this means that create cells
  1763. * can reach us too. */
  1764. router_orport_found_reachable();
  1765. }
  1766. return 0;
  1767. }
  1768. /** Choose a length for a circuit of purpose <b>purpose</b>.
  1769. * Default length is 3 + the number of endpoints that would give something
  1770. * away. If the routerlist <b>routers</b> doesn't have enough routers
  1771. * to handle the desired path length, return as large a path length as
  1772. * is feasible, except if it's less than 2, in which case return -1.
  1773. */
  1774. static int
  1775. new_route_len(uint8_t purpose, extend_info_t *exit,
  1776. smartlist_t *nodes)
  1777. {
  1778. int num_acceptable_routers;
  1779. int routelen;
  1780. tor_assert(nodes);
  1781. routelen = DEFAULT_ROUTE_LEN;
  1782. if (exit &&
  1783. purpose != CIRCUIT_PURPOSE_TESTING &&
  1784. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1785. routelen++;
  1786. num_acceptable_routers = count_acceptable_nodes(nodes);
  1787. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1788. routelen, num_acceptable_routers, smartlist_len(nodes));
  1789. if (num_acceptable_routers < 2) {
  1790. log_info(LD_CIRC,
  1791. "Not enough acceptable routers (%d). Discarding this circuit.",
  1792. num_acceptable_routers);
  1793. return -1;
  1794. }
  1795. if (num_acceptable_routers < routelen) {
  1796. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  1797. routelen, num_acceptable_routers);
  1798. routelen = num_acceptable_routers;
  1799. }
  1800. return routelen;
  1801. }
  1802. /** Return a newly allocated list of uint16_t * for each predicted port not
  1803. * handled by a current circuit. */
  1804. static smartlist_t *
  1805. circuit_get_unhandled_ports(time_t now)
  1806. {
  1807. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1808. circuit_remove_handled_ports(dest);
  1809. return dest;
  1810. }
  1811. /** Return 1 if we already have circuits present or on the way for
  1812. * all anticipated ports. Return 0 if we should make more.
  1813. *
  1814. * If we're returning 0, set need_uptime and need_capacity to
  1815. * indicate any requirements that the unhandled ports have.
  1816. */
  1817. int
  1818. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1819. int *need_capacity)
  1820. {
  1821. int i, enough;
  1822. uint16_t *port;
  1823. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1824. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1825. tor_assert(need_uptime);
  1826. tor_assert(need_capacity);
  1827. // Always predict need_capacity
  1828. *need_capacity = 1;
  1829. enough = (smartlist_len(sl) == 0);
  1830. for (i = 0; i < smartlist_len(sl); ++i) {
  1831. port = smartlist_get(sl, i);
  1832. if (smartlist_string_num_isin(LongLivedServices, *port))
  1833. *need_uptime = 1;
  1834. tor_free(port);
  1835. }
  1836. smartlist_free(sl);
  1837. return enough;
  1838. }
  1839. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1840. * <b>needed_ports</b>, else return 0.
  1841. */
  1842. static int
  1843. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1844. { /* XXXX MOVE */
  1845. int i;
  1846. uint16_t port;
  1847. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1848. addr_policy_result_t r;
  1849. /* alignment issues aren't a worry for this dereference, since
  1850. needed_ports is explicitly a smartlist of uint16_t's */
  1851. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1852. tor_assert(port);
  1853. if (node)
  1854. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1855. else
  1856. continue;
  1857. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1858. return 1;
  1859. }
  1860. return 0;
  1861. }
  1862. /** Return true iff <b>conn</b> needs another general circuit to be
  1863. * built. */
  1864. static int
  1865. ap_stream_wants_exit_attention(connection_t *conn)
  1866. {
  1867. entry_connection_t *entry;
  1868. if (conn->type != CONN_TYPE_AP)
  1869. return 0;
  1870. entry = TO_ENTRY_CONN(conn);
  1871. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1872. !conn->marked_for_close &&
  1873. !(entry->want_onehop) && /* ignore one-hop streams */
  1874. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1875. !(entry->chosen_exit_name) && /* ignore defined streams */
  1876. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1877. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1878. MIN_CIRCUITS_HANDLING_STREAM))
  1879. return 1;
  1880. return 0;
  1881. }
  1882. /** Return a pointer to a suitable router to be the exit node for the
  1883. * general-purpose circuit we're about to build.
  1884. *
  1885. * Look through the connection array, and choose a router that maximizes
  1886. * the number of pending streams that can exit from this router.
  1887. *
  1888. * Return NULL if we can't find any suitable routers.
  1889. */
  1890. static const node_t *
  1891. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1892. {
  1893. int *n_supported;
  1894. int n_pending_connections = 0;
  1895. smartlist_t *connections;
  1896. int best_support = -1;
  1897. int n_best_support=0;
  1898. const or_options_t *options = get_options();
  1899. const smartlist_t *the_nodes;
  1900. const node_t *node=NULL;
  1901. connections = get_connection_array();
  1902. /* Count how many connections are waiting for a circuit to be built.
  1903. * We use this for log messages now, but in the future we may depend on it.
  1904. */
  1905. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1906. {
  1907. if (ap_stream_wants_exit_attention(conn))
  1908. ++n_pending_connections;
  1909. });
  1910. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1911. // n_pending_connections);
  1912. /* Now we count, for each of the routers in the directory, how many
  1913. * of the pending connections could possibly exit from that
  1914. * router (n_supported[i]). (We can't be sure about cases where we
  1915. * don't know the IP address of the pending connection.)
  1916. *
  1917. * -1 means "Don't use this router at all."
  1918. */
  1919. the_nodes = nodelist_get_list();
  1920. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1921. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1922. const int i = node_sl_idx;
  1923. if (router_digest_is_me(node->identity)) {
  1924. n_supported[i] = -1;
  1925. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1926. /* XXX there's probably a reverse predecessor attack here, but
  1927. * it's slow. should we take this out? -RD
  1928. */
  1929. continue;
  1930. }
  1931. if (!node_has_descriptor(node)) {
  1932. n_supported[i] = -1;
  1933. continue;
  1934. }
  1935. if (!node->is_running || node->is_bad_exit) {
  1936. n_supported[i] = -1;
  1937. continue; /* skip routers that are known to be down or bad exits */
  1938. }
  1939. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1940. /* never pick a non-general node as a random exit. */
  1941. n_supported[i] = -1;
  1942. continue;
  1943. }
  1944. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1945. n_supported[i] = -1;
  1946. continue; /* user asked us not to use it, no matter what */
  1947. }
  1948. if (options->ExitNodes &&
  1949. !routerset_contains_node(options->ExitNodes, node)) {
  1950. n_supported[i] = -1;
  1951. continue; /* not one of our chosen exit nodes */
  1952. }
  1953. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1954. n_supported[i] = -1;
  1955. continue; /* skip routers that are not suitable. Don't worry if
  1956. * this makes us reject all the possible routers: if so,
  1957. * we'll retry later in this function with need_update and
  1958. * need_capacity set to 0. */
  1959. }
  1960. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1961. /* if it's invalid and we don't want it */
  1962. n_supported[i] = -1;
  1963. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1964. // router->nickname, i);
  1965. continue; /* skip invalid routers */
  1966. }
  1967. if (options->ExcludeSingleHopRelays &&
  1968. node_allows_single_hop_exits(node)) {
  1969. n_supported[i] = -1;
  1970. continue;
  1971. }
  1972. if (node_exit_policy_rejects_all(node)) {
  1973. n_supported[i] = -1;
  1974. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1975. // router->nickname, i);
  1976. continue; /* skip routers that reject all */
  1977. }
  1978. n_supported[i] = 0;
  1979. /* iterate over connections */
  1980. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1981. if (!ap_stream_wants_exit_attention(conn))
  1982. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1983. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1984. ++n_supported[i];
  1985. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1986. // router->nickname, i, n_supported[i]);
  1987. } else {
  1988. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1989. // router->nickname, i);
  1990. }
  1991. } SMARTLIST_FOREACH_END(conn);
  1992. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1993. /* Leave best_support at -1 if that's where it is, so we can
  1994. * distinguish it later. */
  1995. continue;
  1996. }
  1997. if (n_supported[i] > best_support) {
  1998. /* If this router is better than previous ones, remember its index
  1999. * and goodness, and start counting how many routers are this good. */
  2000. best_support = n_supported[i]; n_best_support=1;
  2001. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2002. // router->nickname);
  2003. } else if (n_supported[i] == best_support) {
  2004. /* If this router is _as good_ as the best one, just increment the
  2005. * count of equally good routers.*/
  2006. ++n_best_support;
  2007. }
  2008. } SMARTLIST_FOREACH_END(node);
  2009. log_info(LD_CIRC,
  2010. "Found %d servers that might support %d/%d pending connections.",
  2011. n_best_support, best_support >= 0 ? best_support : 0,
  2012. n_pending_connections);
  2013. /* If any routers definitely support any pending connections, choose one
  2014. * at random. */
  2015. if (best_support > 0) {
  2016. smartlist_t *supporting = smartlist_new();
  2017. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2018. if (n_supported[node_sl_idx] == best_support)
  2019. smartlist_add(supporting, (void*)node);
  2020. });
  2021. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2022. smartlist_free(supporting);
  2023. } else {
  2024. /* Either there are no pending connections, or no routers even seem to
  2025. * possibly support any of them. Choose a router at random that satisfies
  2026. * at least one predicted exit port. */
  2027. int attempt;
  2028. smartlist_t *needed_ports, *supporting;
  2029. if (best_support == -1) {
  2030. if (need_uptime || need_capacity) {
  2031. log_info(LD_CIRC,
  2032. "We couldn't find any live%s%s routers; falling back "
  2033. "to list of all routers.",
  2034. need_capacity?", fast":"",
  2035. need_uptime?", stable":"");
  2036. tor_free(n_supported);
  2037. return choose_good_exit_server_general(0, 0);
  2038. }
  2039. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2040. "choosing a doomed exit at random.",
  2041. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  2042. }
  2043. supporting = smartlist_new();
  2044. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2045. for (attempt = 0; attempt < 2; attempt++) {
  2046. /* try once to pick only from routers that satisfy a needed port,
  2047. * then if there are none, pick from any that support exiting. */
  2048. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2049. if (n_supported[node_sl_idx] != -1 &&
  2050. (attempt || node_handles_some_port(node, needed_ports))) {
  2051. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2052. // try, router->nickname);
  2053. smartlist_add(supporting, (void*)node);
  2054. }
  2055. } SMARTLIST_FOREACH_END(node);
  2056. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2057. if (node)
  2058. break;
  2059. smartlist_clear(supporting);
  2060. /* If we reach this point, we can't actually support any unhandled
  2061. * predicted ports, so clear all the remaining ones. */
  2062. if (smartlist_len(needed_ports))
  2063. rep_hist_remove_predicted_ports(needed_ports);
  2064. }
  2065. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2066. smartlist_free(needed_ports);
  2067. smartlist_free(supporting);
  2068. }
  2069. tor_free(n_supported);
  2070. if (node) {
  2071. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2072. return node;
  2073. }
  2074. if (options->ExitNodes) {
  2075. log_warn(LD_CIRC,
  2076. "No specified %sexit routers seem to be running: "
  2077. "can't choose an exit.",
  2078. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  2079. }
  2080. return NULL;
  2081. }
  2082. /** Return a pointer to a suitable router to be the exit node for the
  2083. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2084. * if no router is suitable).
  2085. *
  2086. * For general-purpose circuits, pass it off to
  2087. * choose_good_exit_server_general()
  2088. *
  2089. * For client-side rendezvous circuits, choose a random node, weighted
  2090. * toward the preferences in 'options'.
  2091. */
  2092. static const node_t *
  2093. choose_good_exit_server(uint8_t purpose,
  2094. int need_uptime, int need_capacity, int is_internal)
  2095. {
  2096. const or_options_t *options = get_options();
  2097. router_crn_flags_t flags = CRN_NEED_DESC;
  2098. if (need_uptime)
  2099. flags |= CRN_NEED_UPTIME;
  2100. if (need_capacity)
  2101. flags |= CRN_NEED_CAPACITY;
  2102. switch (purpose) {
  2103. case CIRCUIT_PURPOSE_C_GENERAL:
  2104. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2105. flags |= CRN_ALLOW_INVALID;
  2106. if (is_internal) /* pick it like a middle hop */
  2107. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2108. else
  2109. return choose_good_exit_server_general(need_uptime,need_capacity);
  2110. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2111. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  2112. flags |= CRN_ALLOW_INVALID;
  2113. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2114. }
  2115. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2116. tor_fragile_assert();
  2117. return NULL;
  2118. }
  2119. /** Log a warning if the user specified an exit for the circuit that
  2120. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2121. static void
  2122. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2123. {
  2124. const or_options_t *options = get_options();
  2125. routerset_t *rs = options->ExcludeNodes;
  2126. const char *description;
  2127. uint8_t purpose = circ->base_.purpose;
  2128. if (circ->build_state->onehop_tunnel)
  2129. return;
  2130. switch (purpose)
  2131. {
  2132. default:
  2133. case CIRCUIT_PURPOSE_OR:
  2134. case CIRCUIT_PURPOSE_INTRO_POINT:
  2135. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2136. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2137. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2138. (int)purpose,
  2139. circuit_purpose_to_string(purpose));
  2140. return;
  2141. case CIRCUIT_PURPOSE_C_GENERAL:
  2142. if (circ->build_state->is_internal)
  2143. return;
  2144. description = "requested exit node";
  2145. rs = options->ExcludeExitNodesUnion_;
  2146. break;
  2147. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2148. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2149. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2150. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2151. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2152. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2153. case CIRCUIT_PURPOSE_TESTING:
  2154. return;
  2155. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2156. case CIRCUIT_PURPOSE_C_REND_READY:
  2157. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2158. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2159. description = "chosen rendezvous point";
  2160. break;
  2161. case CIRCUIT_PURPOSE_CONTROLLER:
  2162. rs = options->ExcludeExitNodesUnion_;
  2163. description = "controller-selected circuit target";
  2164. break;
  2165. }
  2166. if (routerset_contains_extendinfo(rs, exit)) {
  2167. /* We should never get here if StrictNodes is set to 1. */
  2168. if (options->StrictNodes) {
  2169. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2170. "even though StrictNodes is set. Please report. "
  2171. "(Circuit purpose: %s)",
  2172. description, extend_info_describe(exit),
  2173. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2174. circuit_purpose_to_string(purpose));
  2175. } else {
  2176. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2177. "ExcludeNodes%s, because no better options were available. To "
  2178. "prevent this (and possibly break your Tor functionality), "
  2179. "set the StrictNodes configuration option. "
  2180. "(Circuit purpose: %s)",
  2181. description, extend_info_describe(exit),
  2182. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2183. circuit_purpose_to_string(purpose));
  2184. }
  2185. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2186. }
  2187. return;
  2188. }
  2189. /** Decide a suitable length for circ's cpath, and pick an exit
  2190. * router (or use <b>exit</b> if provided). Store these in the
  2191. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2192. static int
  2193. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2194. {
  2195. cpath_build_state_t *state = circ->build_state;
  2196. if (state->onehop_tunnel) {
  2197. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2198. state->desired_path_len = 1;
  2199. } else {
  2200. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  2201. if (r < 1) /* must be at least 1 */
  2202. return -1;
  2203. state->desired_path_len = r;
  2204. }
  2205. if (exit) { /* the circuit-builder pre-requested one */
  2206. warn_if_last_router_excluded(circ, exit);
  2207. log_info(LD_CIRC,"Using requested exit node '%s'",
  2208. extend_info_describe(exit));
  2209. exit = extend_info_dup(exit);
  2210. } else { /* we have to decide one */
  2211. const node_t *node =
  2212. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  2213. state->need_capacity, state->is_internal);
  2214. if (!node) {
  2215. log_warn(LD_CIRC,"failed to choose an exit server");
  2216. return -1;
  2217. }
  2218. exit = extend_info_from_node(node, 0);
  2219. tor_assert(exit);
  2220. }
  2221. state->chosen_exit = exit;
  2222. return 0;
  2223. }
  2224. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2225. * hop to the cpath reflecting this. Don't send the next extend cell --
  2226. * the caller will do this if it wants to.
  2227. */
  2228. int
  2229. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2230. {
  2231. cpath_build_state_t *state;
  2232. tor_assert(exit);
  2233. tor_assert(circ);
  2234. state = circ->build_state;
  2235. tor_assert(state);
  2236. extend_info_free(state->chosen_exit);
  2237. state->chosen_exit = extend_info_dup(exit);
  2238. ++circ->build_state->desired_path_len;
  2239. onion_append_hop(&circ->cpath, exit);
  2240. return 0;
  2241. }
  2242. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2243. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2244. * send the next extend cell to begin connecting to that hop.
  2245. */
  2246. int
  2247. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2248. {
  2249. int err_reason = 0;
  2250. warn_if_last_router_excluded(circ, exit);
  2251. circuit_append_new_exit(circ, exit);
  2252. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2253. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2254. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2255. extend_info_describe(exit));
  2256. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2257. return -1;
  2258. }
  2259. /* Set timestamp_dirty, so we can check it for path use bias */
  2260. if (!circ->base_.timestamp_dirty)
  2261. circ->base_.timestamp_dirty = time(NULL);
  2262. return 0;
  2263. }
  2264. /** Return the number of routers in <b>routers</b> that are currently up
  2265. * and available for building circuits through.
  2266. */
  2267. static int
  2268. count_acceptable_nodes(smartlist_t *nodes)
  2269. {
  2270. int num=0;
  2271. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2272. // log_debug(LD_CIRC,
  2273. // "Contemplating whether router %d (%s) is a new option.",
  2274. // i, r->nickname);
  2275. if (! node->is_running)
  2276. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2277. continue;
  2278. if (! node->is_valid)
  2279. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2280. continue;
  2281. if (! node_has_descriptor(node))
  2282. continue;
  2283. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2284. * allows this node in some places, then we're getting an inaccurate
  2285. * count. For now, be conservative and don't count it. But later we
  2286. * should try to be smarter. */
  2287. ++num;
  2288. } SMARTLIST_FOREACH_END(node);
  2289. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2290. return num;
  2291. }
  2292. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2293. * This function is used to extend cpath by another hop.
  2294. */
  2295. void
  2296. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2297. {
  2298. if (*head_ptr) {
  2299. new_hop->next = (*head_ptr);
  2300. new_hop->prev = (*head_ptr)->prev;
  2301. (*head_ptr)->prev->next = new_hop;
  2302. (*head_ptr)->prev = new_hop;
  2303. } else {
  2304. *head_ptr = new_hop;
  2305. new_hop->prev = new_hop->next = new_hop;
  2306. }
  2307. }
  2308. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2309. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2310. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2311. * circuit. In particular, make sure we don't pick the exit node or its
  2312. * family, and make sure we don't duplicate any previous nodes or their
  2313. * families. */
  2314. static const node_t *
  2315. choose_good_middle_server(uint8_t purpose,
  2316. cpath_build_state_t *state,
  2317. crypt_path_t *head,
  2318. int cur_len)
  2319. {
  2320. int i;
  2321. const node_t *r, *choice;
  2322. crypt_path_t *cpath;
  2323. smartlist_t *excluded;
  2324. const or_options_t *options = get_options();
  2325. router_crn_flags_t flags = CRN_NEED_DESC;
  2326. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2327. purpose <= CIRCUIT_PURPOSE_MAX_);
  2328. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2329. excluded = smartlist_new();
  2330. if ((r = build_state_get_exit_node(state))) {
  2331. nodelist_add_node_and_family(excluded, r);
  2332. }
  2333. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2334. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2335. nodelist_add_node_and_family(excluded, r);
  2336. }
  2337. }
  2338. if (state->need_uptime)
  2339. flags |= CRN_NEED_UPTIME;
  2340. if (state->need_capacity)
  2341. flags |= CRN_NEED_CAPACITY;
  2342. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2343. flags |= CRN_ALLOW_INVALID;
  2344. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2345. smartlist_free(excluded);
  2346. return choice;
  2347. }
  2348. /** Pick a good entry server for the circuit to be built according to
  2349. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2350. * router (if we're an OR), and respect firewall settings; if we're
  2351. * configured to use entry guards, return one.
  2352. *
  2353. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2354. * guard, not for any particular circuit.
  2355. */
  2356. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2357. const node_t *
  2358. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2359. {
  2360. const node_t *choice;
  2361. smartlist_t *excluded;
  2362. const or_options_t *options = get_options();
  2363. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2364. const node_t *node;
  2365. if (state && options->UseEntryGuards &&
  2366. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2367. /* This request is for an entry server to use for a regular circuit,
  2368. * and we use entry guard nodes. Just return one of the guard nodes. */
  2369. return choose_random_entry(state);
  2370. }
  2371. excluded = smartlist_new();
  2372. if (state && (node = build_state_get_exit_node(state))) {
  2373. /* Exclude the exit node from the state, if we have one. Also exclude its
  2374. * family. */
  2375. nodelist_add_node_and_family(excluded, node);
  2376. }
  2377. if (firewall_is_fascist_or()) {
  2378. /* Exclude all ORs that we can't reach through our firewall */
  2379. smartlist_t *nodes = nodelist_get_list();
  2380. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2381. if (!fascist_firewall_allows_node(node))
  2382. smartlist_add(excluded, (void*)node);
  2383. });
  2384. }
  2385. /* and exclude current entry guards and their families, if applicable */
  2386. if (options->UseEntryGuards) {
  2387. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2388. {
  2389. if ((node = node_get_by_id(entry->identity))) {
  2390. nodelist_add_node_and_family(excluded, node);
  2391. }
  2392. });
  2393. }
  2394. if (state) {
  2395. if (state->need_uptime)
  2396. flags |= CRN_NEED_UPTIME;
  2397. if (state->need_capacity)
  2398. flags |= CRN_NEED_CAPACITY;
  2399. }
  2400. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  2401. flags |= CRN_ALLOW_INVALID;
  2402. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2403. smartlist_free(excluded);
  2404. return choice;
  2405. }
  2406. /** Return the first non-open hop in cpath, or return NULL if all
  2407. * hops are open. */
  2408. static crypt_path_t *
  2409. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2410. {
  2411. crypt_path_t *hop = cpath;
  2412. do {
  2413. if (hop->state != CPATH_STATE_OPEN)
  2414. return hop;
  2415. hop = hop->next;
  2416. } while (hop != cpath);
  2417. return NULL;
  2418. }
  2419. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2420. * based on <b>state</b>. Append the hop info to head_ptr.
  2421. */
  2422. static int
  2423. onion_extend_cpath(origin_circuit_t *circ)
  2424. {
  2425. uint8_t purpose = circ->base_.purpose;
  2426. cpath_build_state_t *state = circ->build_state;
  2427. int cur_len = circuit_get_cpath_len(circ);
  2428. extend_info_t *info = NULL;
  2429. if (cur_len >= state->desired_path_len) {
  2430. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2431. state->desired_path_len);
  2432. return 1;
  2433. }
  2434. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2435. state->desired_path_len);
  2436. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2437. info = extend_info_dup(state->chosen_exit);
  2438. } else if (cur_len == 0) { /* picking first node */
  2439. const node_t *r = choose_good_entry_server(purpose, state);
  2440. if (r) {
  2441. /* If we're a client, use the preferred address rather than the
  2442. primary address, for potentially connecting to an IPv6 OR
  2443. port. */
  2444. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  2445. tor_assert(info);
  2446. }
  2447. } else {
  2448. const node_t *r =
  2449. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2450. if (r) {
  2451. info = extend_info_from_node(r, 0);
  2452. tor_assert(info);
  2453. }
  2454. }
  2455. if (!info) {
  2456. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2457. "this circuit.", cur_len);
  2458. return -1;
  2459. }
  2460. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2461. extend_info_describe(info),
  2462. cur_len+1, build_state_get_exit_nickname(state));
  2463. onion_append_hop(&circ->cpath, info);
  2464. extend_info_free(info);
  2465. return 0;
  2466. }
  2467. /** Create a new hop, annotate it with information about its
  2468. * corresponding router <b>choice</b>, and append it to the
  2469. * end of the cpath <b>head_ptr</b>. */
  2470. static int
  2471. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2472. {
  2473. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2474. /* link hop into the cpath, at the end. */
  2475. onion_append_to_cpath(head_ptr, hop);
  2476. hop->magic = CRYPT_PATH_MAGIC;
  2477. hop->state = CPATH_STATE_CLOSED;
  2478. hop->extend_info = extend_info_dup(choice);
  2479. hop->package_window = circuit_initial_package_window();
  2480. hop->deliver_window = CIRCWINDOW_START;
  2481. return 0;
  2482. }
  2483. /** Allocate a new extend_info object based on the various arguments. */
  2484. extend_info_t *
  2485. extend_info_new(const char *nickname, const char *digest,
  2486. crypto_pk_t *onion_key,
  2487. const tor_addr_t *addr, uint16_t port)
  2488. {
  2489. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2490. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2491. if (nickname)
  2492. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2493. if (onion_key)
  2494. info->onion_key = crypto_pk_dup_key(onion_key);
  2495. tor_addr_copy(&info->addr, addr);
  2496. info->port = port;
  2497. return info;
  2498. }
  2499. /** Allocate and return a new extend_info that can be used to build a
  2500. * circuit to or through the node <b>node</b>. Use the primary address
  2501. * of the node (i.e. its IPv4 address) unless
  2502. * <b>for_direct_connect</b> is true, in which case the preferred
  2503. * address is used instead. May return NULL if there is not enough
  2504. * info about <b>node</b> to extend to it--for example, if there is no
  2505. * routerinfo_t or microdesc_t.
  2506. **/
  2507. extend_info_t *
  2508. extend_info_from_node(const node_t *node, int for_direct_connect)
  2509. {
  2510. tor_addr_port_t ap;
  2511. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2512. return NULL;
  2513. if (for_direct_connect)
  2514. node_get_pref_orport(node, &ap);
  2515. else
  2516. node_get_prim_orport(node, &ap);
  2517. log_debug(LD_CIRC, "using %s for %s",
  2518. fmt_addrport(&ap.addr, ap.port),
  2519. node->ri ? node->ri->nickname : node->rs->nickname);
  2520. if (node->ri)
  2521. return extend_info_new(node->ri->nickname,
  2522. node->identity,
  2523. node->ri->onion_pkey,
  2524. &ap.addr,
  2525. ap.port);
  2526. else if (node->rs && node->md)
  2527. return extend_info_new(node->rs->nickname,
  2528. node->identity,
  2529. node->md->onion_pkey,
  2530. &ap.addr,
  2531. ap.port);
  2532. else
  2533. return NULL;
  2534. }
  2535. /** Release storage held by an extend_info_t struct. */
  2536. void
  2537. extend_info_free(extend_info_t *info)
  2538. {
  2539. if (!info)
  2540. return;
  2541. crypto_pk_free(info->onion_key);
  2542. tor_free(info);
  2543. }
  2544. /** Allocate and return a new extend_info_t with the same contents as
  2545. * <b>info</b>. */
  2546. extend_info_t *
  2547. extend_info_dup(extend_info_t *info)
  2548. {
  2549. extend_info_t *newinfo;
  2550. tor_assert(info);
  2551. newinfo = tor_malloc(sizeof(extend_info_t));
  2552. memcpy(newinfo, info, sizeof(extend_info_t));
  2553. if (info->onion_key)
  2554. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2555. else
  2556. newinfo->onion_key = NULL;
  2557. return newinfo;
  2558. }
  2559. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2560. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2561. * the chosen exit, return NULL.
  2562. */
  2563. const node_t *
  2564. build_state_get_exit_node(cpath_build_state_t *state)
  2565. {
  2566. if (!state || !state->chosen_exit)
  2567. return NULL;
  2568. return node_get_by_id(state->chosen_exit->identity_digest);
  2569. }
  2570. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2571. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2572. * chosen exit, return NULL.
  2573. */
  2574. const char *
  2575. build_state_get_exit_nickname(cpath_build_state_t *state)
  2576. {
  2577. if (!state || !state->chosen_exit)
  2578. return NULL;
  2579. return state->chosen_exit->nickname;
  2580. }