circuitbuild.c 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819
  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_first_hop_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 first hop completions 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_DID_FIRST_HOP:
  1027. return "first hop";
  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. * Decide if the path bias code should count a circuit.
  1037. *
  1038. * @returns 1 if we should count it, 0 otherwise.
  1039. */
  1040. static int
  1041. pathbias_should_count(origin_circuit_t *circ)
  1042. {
  1043. #define PATHBIAS_COUNT_INTERVAL (600)
  1044. static ratelim_t count_limit =
  1045. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  1046. char *rate_msg = NULL;
  1047. /* We can't do path bias accounting without entry guards.
  1048. * Testing and controller circuits also have no guards.
  1049. *
  1050. * We also don't count server-side rends, because their
  1051. * endpoint could be chosen maliciously.
  1052. * Similarly, we can't count client-side intro attempts,
  1053. * because clients can be manipulated into connecting to
  1054. * malicious intro points. */
  1055. if (get_options()->UseEntryGuards == 0 ||
  1056. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1057. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  1058. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1059. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  1060. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1061. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  1062. return 0;
  1063. }
  1064. /* Completely ignore one hop circuits */
  1065. if (circ->build_state->onehop_tunnel ||
  1066. circ->build_state->desired_path_len == 1) {
  1067. /* Check for inconsistency */
  1068. if (circ->build_state->desired_path_len != 1 ||
  1069. !circ->build_state->onehop_tunnel) {
  1070. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  1071. log_notice(LD_BUG,
  1072. "One-hop circuit has length %d. Path state is %s. "
  1073. "Circuit is a %s currently %s.%s",
  1074. circ->build_state->desired_path_len,
  1075. pathbias_state_to_string(circ->path_state),
  1076. circuit_purpose_to_string(circ->base_.purpose),
  1077. circuit_state_to_string(circ->base_.state),
  1078. rate_msg);
  1079. tor_free(rate_msg);
  1080. }
  1081. tor_fragile_assert();
  1082. }
  1083. return 0;
  1084. }
  1085. return 1;
  1086. }
  1087. /**
  1088. * Check our circuit state to see if this is a successful first hop.
  1089. * If so, record it in the current guard's path bias first_hop count.
  1090. *
  1091. * Also check for several potential error cases for bug #6475.
  1092. */
  1093. static int
  1094. pathbias_count_first_hop(origin_circuit_t *circ)
  1095. {
  1096. #define FIRST_HOP_NOTICE_INTERVAL (600)
  1097. static ratelim_t first_hop_notice_limit =
  1098. RATELIM_INIT(FIRST_HOP_NOTICE_INTERVAL);
  1099. char *rate_msg = NULL;
  1100. if (!pathbias_should_count(circ)) {
  1101. return 0;
  1102. }
  1103. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1104. /* Help track down the real cause of bug #6475: */
  1105. if (circ->has_opened && circ->path_state != PATH_STATE_DID_FIRST_HOP) {
  1106. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1107. approx_time()))) {
  1108. log_info(LD_BUG,
  1109. "Opened circuit is in strange path state %s. "
  1110. "Circuit is a %s currently %s.%s",
  1111. pathbias_state_to_string(circ->path_state),
  1112. circuit_purpose_to_string(circ->base_.purpose),
  1113. circuit_state_to_string(circ->base_.state),
  1114. rate_msg);
  1115. tor_free(rate_msg);
  1116. }
  1117. }
  1118. /* Don't re-count cannibalized circs.. */
  1119. if (!circ->has_opened) {
  1120. entry_guard_t *guard = NULL;
  1121. if (circ->cpath && circ->cpath->extend_info) {
  1122. guard = entry_guard_get_by_id_digest(
  1123. circ->cpath->extend_info->identity_digest);
  1124. } else if (circ->base_.n_chan) {
  1125. guard =
  1126. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1127. }
  1128. if (guard) {
  1129. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1130. circ->path_state = PATH_STATE_DID_FIRST_HOP;
  1131. if (entry_guard_inc_first_hop_count(guard) < 0) {
  1132. /* Bogus guard; we already warned. */
  1133. return -END_CIRC_REASON_TORPROTOCOL;
  1134. }
  1135. } else {
  1136. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1137. approx_time()))) {
  1138. log_info(LD_BUG,
  1139. "Unopened circuit has strange path state %s. "
  1140. "Circuit is a %s currently %s.%s",
  1141. pathbias_state_to_string(circ->path_state),
  1142. circuit_purpose_to_string(circ->base_.purpose),
  1143. circuit_state_to_string(circ->base_.state),
  1144. rate_msg);
  1145. tor_free(rate_msg);
  1146. }
  1147. }
  1148. } else {
  1149. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1150. approx_time()))) {
  1151. log_info(LD_BUG,
  1152. "Unopened circuit has no known guard. "
  1153. "Circuit is a %s currently %s.%s",
  1154. circuit_purpose_to_string(circ->base_.purpose),
  1155. circuit_state_to_string(circ->base_.state),
  1156. rate_msg);
  1157. tor_free(rate_msg);
  1158. }
  1159. }
  1160. }
  1161. } else {
  1162. /* Help track down the real cause of bug #6475: */
  1163. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1164. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1165. approx_time()))) {
  1166. log_info(LD_BUG,
  1167. "A %s circuit is in cpath state %d (opened: %d). "
  1168. "Circuit is a %s currently %s.%s",
  1169. pathbias_state_to_string(circ->path_state),
  1170. circ->cpath->state, circ->has_opened,
  1171. circuit_purpose_to_string(circ->base_.purpose),
  1172. circuit_state_to_string(circ->base_.state),
  1173. rate_msg);
  1174. tor_free(rate_msg);
  1175. }
  1176. }
  1177. }
  1178. return 0;
  1179. }
  1180. /**
  1181. * Check our circuit state to see if this is a successful circuit
  1182. * completion. If so, record it in the current guard's path bias
  1183. * success count.
  1184. *
  1185. * Also check for several potential error cases for bug #6475.
  1186. */
  1187. static void
  1188. pathbias_count_build_success(origin_circuit_t *circ)
  1189. {
  1190. #define SUCCESS_NOTICE_INTERVAL (600)
  1191. static ratelim_t success_notice_limit =
  1192. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1193. char *rate_msg = NULL;
  1194. entry_guard_t *guard = NULL;
  1195. if (!pathbias_should_count(circ)) {
  1196. return;
  1197. }
  1198. /* Don't count cannibalized/reused circs for path bias
  1199. * build success.. They get counted under use success */
  1200. if (!circ->has_opened) {
  1201. if (circ->cpath && circ->cpath->extend_info) {
  1202. guard = entry_guard_get_by_id_digest(
  1203. circ->cpath->extend_info->identity_digest);
  1204. }
  1205. if (guard) {
  1206. if (circ->path_state == PATH_STATE_DID_FIRST_HOP) {
  1207. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  1208. guard->circuit_successes++;
  1209. log_info(LD_CIRC, "Got success count %u/%u for guard %s=%s",
  1210. guard->circuit_successes, guard->first_hops,
  1211. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1212. } else {
  1213. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1214. approx_time()))) {
  1215. log_info(LD_BUG,
  1216. "Succeeded circuit is in strange path state %s. "
  1217. "Circuit is a %s currently %s.%s",
  1218. pathbias_state_to_string(circ->path_state),
  1219. circuit_purpose_to_string(circ->base_.purpose),
  1220. circuit_state_to_string(circ->base_.state),
  1221. rate_msg);
  1222. tor_free(rate_msg);
  1223. }
  1224. }
  1225. if (guard->first_hops < guard->circuit_successes) {
  1226. log_notice(LD_BUG, "Unexpectedly high circuit_successes (%u/%u) "
  1227. "for guard %s=%s",
  1228. guard->circuit_successes, guard->first_hops,
  1229. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1230. }
  1231. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1232. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1233. * No need to log that case. */
  1234. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1235. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1236. approx_time()))) {
  1237. log_info(LD_BUG,
  1238. "Completed circuit has no known guard. "
  1239. "Circuit is a %s currently %s.%s",
  1240. circuit_purpose_to_string(circ->base_.purpose),
  1241. circuit_state_to_string(circ->base_.state),
  1242. rate_msg);
  1243. tor_free(rate_msg);
  1244. }
  1245. }
  1246. } else {
  1247. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  1248. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1249. approx_time()))) {
  1250. log_info(LD_BUG,
  1251. "Opened circuit is in strange path state %s. "
  1252. "Circuit is a %s currently %s.%s",
  1253. pathbias_state_to_string(circ->path_state),
  1254. circuit_purpose_to_string(circ->base_.purpose),
  1255. circuit_state_to_string(circ->base_.state),
  1256. rate_msg);
  1257. tor_free(rate_msg);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. /**
  1263. * Check if a circuit was used and/or closed successfully.
  1264. */
  1265. void
  1266. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  1267. {
  1268. circuit_t *circ = &ocirc->base_;
  1269. if (!pathbias_should_count(ocirc)) {
  1270. return;
  1271. }
  1272. if (ocirc->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1273. if (circ->timestamp_dirty) {
  1274. /* Any circuit where there were attempted streams but no successful
  1275. * streams could be bias */
  1276. // XXX: May open up attacks if the adversary can force connections
  1277. // on unresponsive hosts to use new circs. Vidalia displayes a "Retrying"
  1278. // state.. Can we use that? Does optimistic data change this?
  1279. log_info(LD_CIRC,
  1280. "Circuit closed without successful use for reason %d. "
  1281. "Circuit purpose %d currently %s.",
  1282. reason, circ->purpose, circuit_state_to_string(circ->state));
  1283. pathbias_count_unusable(ocirc);
  1284. } else {
  1285. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  1286. /* Unused remote circ close reasons all could be bias */
  1287. log_info(LD_CIRC,
  1288. "Circuit remote-closed without successful use for reason %d. "
  1289. "Circuit purpose %d currently %s.",
  1290. reason, circ->purpose, circuit_state_to_string(circ->state));
  1291. pathbias_count_collapse(ocirc);
  1292. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  1293. == END_CIRC_REASON_CHANNEL_CLOSED &&
  1294. circ->n_chan &&
  1295. circ->n_chan->reason_for_closing
  1296. != CHANNEL_CLOSE_REQUESTED) {
  1297. /* If we didn't close the channel ourselves, it could be bias */
  1298. /* FIXME: Only count bias if the network is live?
  1299. * What about clock jumps/suspends? */
  1300. log_info(LD_CIRC,
  1301. "Circuit's channel closed without successful use for reason %d, "
  1302. "channel reason %d. Circuit purpose %d currently %s.",
  1303. reason, circ->n_chan->reason_for_closing,
  1304. circ->purpose, circuit_state_to_string(circ->state));
  1305. pathbias_count_collapse(ocirc);
  1306. } else {
  1307. pathbias_count_successful_close(ocirc);
  1308. }
  1309. }
  1310. } else if (ocirc->path_state == PATH_STATE_USE_SUCCEEDED) {
  1311. pathbias_count_successful_close(ocirc);
  1312. }
  1313. }
  1314. /**
  1315. * Count a successfully closed circuit.
  1316. */
  1317. static void
  1318. pathbias_count_successful_close(origin_circuit_t *circ)
  1319. {
  1320. entry_guard_t *guard = NULL;
  1321. if (!pathbias_should_count(circ)) {
  1322. return;
  1323. }
  1324. if (circ->cpath && circ->cpath->extend_info) {
  1325. guard = entry_guard_get_by_id_digest(
  1326. circ->cpath->extend_info->identity_digest);
  1327. }
  1328. if (guard) {
  1329. /* In the long run: circuit_success ~= successful_circuit_close +
  1330. * circ_failure + stream_failure */
  1331. guard->successful_circuits_closed++;
  1332. entry_guards_changed();
  1333. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1334. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1335. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1336. * No need to log that case. */
  1337. log_info(LD_BUG,
  1338. "Successfully closed circuit has no known guard. "
  1339. "Circuit is a %s currently %s",
  1340. circuit_purpose_to_string(circ->base_.purpose),
  1341. circuit_state_to_string(circ->base_.state));
  1342. }
  1343. }
  1344. /**
  1345. * Count a circuit that fails after it is built, but before it can
  1346. * carry any traffic.
  1347. *
  1348. * This is needed because there are ways to destroy a
  1349. * circuit after it has successfully completed. Right now, this is
  1350. * used for purely informational/debugging purposes.
  1351. */
  1352. static void
  1353. pathbias_count_collapse(origin_circuit_t *circ)
  1354. {
  1355. entry_guard_t *guard = NULL;
  1356. if (!pathbias_should_count(circ)) {
  1357. return;
  1358. }
  1359. if (circ->cpath && circ->cpath->extend_info) {
  1360. guard = entry_guard_get_by_id_digest(
  1361. circ->cpath->extend_info->identity_digest);
  1362. }
  1363. if (guard) {
  1364. guard->collapsed_circuits++;
  1365. entry_guards_changed();
  1366. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1367. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1368. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1369. * No need to log that case. */
  1370. log_info(LD_BUG,
  1371. "Destroyed circuit has no known guard. "
  1372. "Circuit is a %s currently %s",
  1373. circuit_purpose_to_string(circ->base_.purpose),
  1374. circuit_state_to_string(circ->base_.state));
  1375. }
  1376. }
  1377. static void
  1378. pathbias_count_unusable(origin_circuit_t *circ)
  1379. {
  1380. entry_guard_t *guard = NULL;
  1381. if (!pathbias_should_count(circ)) {
  1382. return;
  1383. }
  1384. if (circ->cpath && circ->cpath->extend_info) {
  1385. guard = entry_guard_get_by_id_digest(
  1386. circ->cpath->extend_info->identity_digest);
  1387. }
  1388. if (guard) {
  1389. guard->unusable_circuits++;
  1390. entry_guards_changed();
  1391. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1392. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1393. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1394. * No need to log that case. */
  1395. log_info(LD_BUG,
  1396. "Stream-failing circuit has no known guard. "
  1397. "Circuit is a %s currently %s",
  1398. circuit_purpose_to_string(circ->base_.purpose),
  1399. circuit_state_to_string(circ->base_.state));
  1400. }
  1401. }
  1402. /**
  1403. * Count timeouts for path bias log messages.
  1404. *
  1405. * These counts are purely informational.
  1406. */
  1407. void
  1408. pathbias_count_timeout(origin_circuit_t *circ)
  1409. {
  1410. entry_guard_t *guard = NULL;
  1411. if (!pathbias_should_count(circ)) {
  1412. return;
  1413. }
  1414. /* For hidden service circs, they can actually be used
  1415. * successfully and then time out later (because
  1416. * the other side declines to use them). */
  1417. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1418. return;
  1419. }
  1420. if (circ->cpath && circ->cpath->extend_info) {
  1421. guard = entry_guard_get_by_id_digest(
  1422. circ->cpath->extend_info->identity_digest);
  1423. }
  1424. if (guard) {
  1425. guard->timeouts++;
  1426. entry_guards_changed();
  1427. }
  1428. }
  1429. // XXX: DOCDOC
  1430. int
  1431. pathbias_get_closed_count(entry_guard_t *guard)
  1432. {
  1433. circuit_t *circ = global_circuitlist;
  1434. int open_circuits = 0;
  1435. /* Count currently open circuits. Give them the benefit of the doubt */
  1436. for ( ; circ; circ = circ->next) {
  1437. origin_circuit_t *ocirc = NULL;
  1438. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1439. circ->marked_for_close) /* already counted */
  1440. continue;
  1441. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1442. if(!ocirc->cpath || !ocirc->cpath->extend_info)
  1443. continue;
  1444. if (ocirc->path_state >= PATH_STATE_BUILD_SUCCEEDED &&
  1445. (memcmp(guard->identity,
  1446. ocirc->cpath->extend_info->identity_digest,
  1447. DIGEST_LEN)
  1448. == 0)) {
  1449. open_circuits++;
  1450. }
  1451. }
  1452. return guard->successful_circuits_closed + open_circuits;
  1453. }
  1454. /**
  1455. * This function checks the consensus parameters to decide
  1456. * if it should return guard->circuit_successes or
  1457. * guard->successful_circuits_closed.
  1458. */
  1459. static int
  1460. pathbias_get_success_count(entry_guard_t *guard)
  1461. {
  1462. if (pathbias_use_close_counts(get_options())) {
  1463. return pathbias_get_closed_count(guard);
  1464. } else {
  1465. return guard->circuit_successes;
  1466. }
  1467. }
  1468. /** Increment the number of times we successfully extended a circuit to
  1469. * 'guard', first checking if the failure rate is high enough that we should
  1470. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  1471. * guard looks fine. */
  1472. static int
  1473. entry_guard_inc_first_hop_count(entry_guard_t *guard)
  1474. {
  1475. const or_options_t *options = get_options();
  1476. entry_guards_changed();
  1477. if (guard->first_hops > (unsigned)pathbias_get_min_circs(options)) {
  1478. /* Note: We rely on the < comparison here to allow us to set a 0
  1479. * rate and disable the feature entirely. If refactoring, don't
  1480. * change to <= */
  1481. if (pathbias_get_success_count(guard)/((double)guard->first_hops)
  1482. < pathbias_get_extreme_rate(options)) {
  1483. /* Dropping is currently disabled by default. */
  1484. if (pathbias_get_dropguards(options)) {
  1485. if (!guard->path_bias_disabled) {
  1486. log_warn(LD_CIRC,
  1487. "Your Guard %s=%s is failing an extremely large amount of "
  1488. "circuits. To avoid potential route manipluation attacks, "
  1489. "Tor has disabled use of this guard. "
  1490. "Success counts are %d/%d. %d circuits completed, %d "
  1491. "were unusable, %d collapsed, and %d timed out. For "
  1492. "reference, your timeout cutoff is %ld seconds.",
  1493. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1494. pathbias_get_closed_count(guard), guard->first_hops,
  1495. guard->circuit_successes, guard->unusable_circuits,
  1496. guard->collapsed_circuits, guard->timeouts,
  1497. (long)circ_times.close_ms/1000);
  1498. guard->path_bias_disabled = 1;
  1499. guard->bad_since = approx_time();
  1500. return -1;
  1501. }
  1502. } else if (!guard->path_bias_extreme) {
  1503. guard->path_bias_extreme = 1;
  1504. log_warn(LD_CIRC,
  1505. "Your Guard %s=%s is failing an extremely large amount of "
  1506. "circuits. This could indicate a route manipulation attack, "
  1507. "extreme network overload, or a bug. "
  1508. "Success counts are %d/%d. %d circuits completed, %d "
  1509. "were unusable, %d collapsed, and %d timed out. For "
  1510. "reference, your timeout cutoff is %ld seconds.",
  1511. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1512. pathbias_get_closed_count(guard), guard->first_hops,
  1513. guard->circuit_successes, guard->unusable_circuits,
  1514. guard->collapsed_circuits, guard->timeouts,
  1515. (long)circ_times.close_ms/1000);
  1516. }
  1517. } else if (pathbias_get_success_count(guard)/((double)guard->first_hops)
  1518. < pathbias_get_warn_rate(options)) {
  1519. if (!guard->path_bias_warned) {
  1520. guard->path_bias_warned = 1;
  1521. log_warn(LD_CIRC,
  1522. "Your Guard %s=%s is failing a very large amount of "
  1523. "circuits. Most likely this means the Tor network is "
  1524. "overloaded, but it could also mean an attack against "
  1525. "you or the potentially the guard itself. "
  1526. "Success counts are %d/%d. %d circuits completed, %d "
  1527. "were unusable, %d collapsed, and %d timed out. For "
  1528. "reference, your timeout cutoff is %ld seconds.",
  1529. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1530. pathbias_get_closed_count(guard), guard->first_hops,
  1531. guard->circuit_successes, guard->unusable_circuits,
  1532. guard->collapsed_circuits, guard->timeouts,
  1533. (long)circ_times.close_ms/1000);
  1534. }
  1535. } else if (pathbias_get_success_count(guard)/((double)guard->first_hops)
  1536. < pathbias_get_notice_rate(options)) {
  1537. if (!guard->path_bias_noticed) {
  1538. guard->path_bias_noticed = 1;
  1539. log_notice(LD_CIRC,
  1540. "Your Guard %s=%s is failing more circuits than usual. "
  1541. "Most likely this means the Tor network is overloaded. "
  1542. "Success counts are %d/%d. %d circuits completed, %d "
  1543. "were unusable, %d collapsed, and %d timed out. For "
  1544. "reference, your timeout cutoff is %ld seconds.",
  1545. guard->nickname, hex_str(guard->identity, DIGEST_LEN),
  1546. pathbias_get_closed_count(guard), guard->first_hops,
  1547. guard->circuit_successes, guard->unusable_circuits,
  1548. guard->collapsed_circuits, guard->timeouts,
  1549. (long)circ_times.close_ms/1000);
  1550. }
  1551. }
  1552. }
  1553. /* If we get a ton of circuits, just scale everything down */
  1554. if (guard->first_hops > (unsigned)pathbias_get_scale_threshold(options)) {
  1555. const int scale_factor = pathbias_get_scale_factor(options);
  1556. const int mult_factor = pathbias_get_mult_factor(options);
  1557. /* Only scale if there will be no rounding error for our scaling
  1558. * factors */
  1559. if (((mult_factor*guard->first_hops) % scale_factor) == 0 &&
  1560. ((mult_factor*guard->circuit_successes) % scale_factor) == 0) {
  1561. log_info(LD_CIRC,
  1562. "Scaling pathbias counts to (%u/%u)*(%d/%d) for guard %s=%s",
  1563. guard->circuit_successes, guard->first_hops, mult_factor,
  1564. scale_factor, guard->nickname, hex_str(guard->identity,
  1565. DIGEST_LEN));
  1566. guard->first_hops *= mult_factor;
  1567. guard->circuit_successes *= mult_factor;
  1568. guard->timeouts *= mult_factor;
  1569. guard->successful_circuits_closed *= mult_factor;
  1570. guard->collapsed_circuits *= mult_factor;
  1571. guard->unusable_circuits *= mult_factor;
  1572. guard->first_hops /= scale_factor;
  1573. guard->circuit_successes /= scale_factor;
  1574. guard->timeouts /= scale_factor;
  1575. guard->successful_circuits_closed /= scale_factor;
  1576. guard->collapsed_circuits /= scale_factor;
  1577. guard->unusable_circuits /= scale_factor;
  1578. }
  1579. }
  1580. guard->first_hops++;
  1581. log_info(LD_CIRC, "Got success count %u/%u for guard %s=%s",
  1582. guard->circuit_successes, guard->first_hops, guard->nickname,
  1583. hex_str(guard->identity, DIGEST_LEN));
  1584. return 0;
  1585. }
  1586. /** A created or extended cell came back to us on the circuit, and it included
  1587. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  1588. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  1589. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  1590. *
  1591. * Calculate the appropriate keys and digests, make sure KH is
  1592. * correct, and initialize this hop of the cpath.
  1593. *
  1594. * Return - reason if we want to mark circ for close, else return 0.
  1595. */
  1596. int
  1597. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  1598. const uint8_t *reply)
  1599. {
  1600. char keys[CPATH_KEY_MATERIAL_LEN];
  1601. crypt_path_t *hop;
  1602. int rv;
  1603. if ((rv = pathbias_count_first_hop(circ)) < 0)
  1604. return rv;
  1605. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1606. hop = circ->cpath;
  1607. } else {
  1608. hop = onion_next_hop_in_cpath(circ->cpath);
  1609. if (!hop) { /* got an extended when we're all done? */
  1610. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1611. return - END_CIRC_REASON_TORPROTOCOL;
  1612. }
  1613. }
  1614. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1615. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  1616. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  1617. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1618. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1619. return -END_CIRC_REASON_TORPROTOCOL;
  1620. }
  1621. /* Remember hash of g^xy */
  1622. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  1623. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  1624. if (fast_client_handshake(hop->fast_handshake_state, reply,
  1625. (uint8_t*)keys,
  1626. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1627. log_warn(LD_CIRC,"fast_client_handshake failed.");
  1628. return -END_CIRC_REASON_TORPROTOCOL;
  1629. }
  1630. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  1631. } else {
  1632. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  1633. return -END_CIRC_REASON_TORPROTOCOL;
  1634. }
  1635. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  1636. hop->dh_handshake_state = NULL;
  1637. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  1638. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1639. return -END_CIRC_REASON_TORPROTOCOL;
  1640. }
  1641. hop->state = CPATH_STATE_OPEN;
  1642. log_info(LD_CIRC,"Finished building %scircuit hop:",
  1643. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  1644. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1645. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1646. return 0;
  1647. }
  1648. /** We received a relay truncated cell on circ.
  1649. *
  1650. * Since we don't ask for truncates currently, getting a truncated
  1651. * means that a connection broke or an extend failed. For now,
  1652. * just give up: for circ to close, and return 0.
  1653. */
  1654. int
  1655. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1656. {
  1657. // crypt_path_t *victim;
  1658. // connection_t *stream;
  1659. tor_assert(circ);
  1660. tor_assert(layer);
  1661. /* XXX Since we don't ask for truncates currently, getting a truncated
  1662. * means that a connection broke or an extend failed. For now,
  1663. * just give up.
  1664. */
  1665. circuit_mark_for_close(TO_CIRCUIT(circ),
  1666. END_CIRC_REASON_FLAG_REMOTE|reason);
  1667. return 0;
  1668. #if 0
  1669. while (layer->next != circ->cpath) {
  1670. /* we need to clear out layer->next */
  1671. victim = layer->next;
  1672. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1673. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1674. if (stream->cpath_layer == victim) {
  1675. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1676. stream->stream_id);
  1677. /* no need to send 'end' relay cells,
  1678. * because the other side's already dead
  1679. */
  1680. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1681. }
  1682. }
  1683. layer->next = victim->next;
  1684. circuit_free_cpath_node(victim);
  1685. }
  1686. log_info(LD_CIRC, "finished");
  1687. return 0;
  1688. #endif
  1689. }
  1690. /** Given a response payload and keys, initialize, then send a created
  1691. * cell back.
  1692. */
  1693. int
  1694. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  1695. const char *keys)
  1696. {
  1697. cell_t cell;
  1698. crypt_path_t *tmp_cpath;
  1699. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1700. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1701. memset(&cell, 0, sizeof(cell_t));
  1702. cell.command = cell_type;
  1703. cell.circ_id = circ->p_circ_id;
  1704. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1705. memcpy(cell.payload, payload,
  1706. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  1707. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1708. (unsigned int)get_uint32(keys),
  1709. (unsigned int)get_uint32(keys+20));
  1710. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1711. log_warn(LD_BUG,"Circuit initialization failed");
  1712. tor_free(tmp_cpath);
  1713. return -1;
  1714. }
  1715. circ->n_digest = tmp_cpath->f_digest;
  1716. circ->n_crypto = tmp_cpath->f_crypto;
  1717. circ->p_digest = tmp_cpath->b_digest;
  1718. circ->p_crypto = tmp_cpath->b_crypto;
  1719. tmp_cpath->magic = 0;
  1720. tor_free(tmp_cpath);
  1721. if (cell_type == CELL_CREATED)
  1722. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  1723. else
  1724. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  1725. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  1726. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1727. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1728. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1729. circ->is_first_hop ? "created_fast" : "created");
  1730. if (!channel_is_local(circ->p_chan) &&
  1731. !channel_is_outgoing(circ->p_chan)) {
  1732. /* record that we could process create cells from a non-local conn
  1733. * that we didn't initiate; presumably this means that create cells
  1734. * can reach us too. */
  1735. router_orport_found_reachable();
  1736. }
  1737. return 0;
  1738. }
  1739. /** Choose a length for a circuit of purpose <b>purpose</b>.
  1740. * Default length is 3 + the number of endpoints that would give something
  1741. * away. If the routerlist <b>routers</b> doesn't have enough routers
  1742. * to handle the desired path length, return as large a path length as
  1743. * is feasible, except if it's less than 2, in which case return -1.
  1744. */
  1745. static int
  1746. new_route_len(uint8_t purpose, extend_info_t *exit,
  1747. smartlist_t *nodes)
  1748. {
  1749. int num_acceptable_routers;
  1750. int routelen;
  1751. tor_assert(nodes);
  1752. routelen = DEFAULT_ROUTE_LEN;
  1753. if (exit &&
  1754. purpose != CIRCUIT_PURPOSE_TESTING &&
  1755. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1756. routelen++;
  1757. num_acceptable_routers = count_acceptable_nodes(nodes);
  1758. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1759. routelen, num_acceptable_routers, smartlist_len(nodes));
  1760. if (num_acceptable_routers < 2) {
  1761. log_info(LD_CIRC,
  1762. "Not enough acceptable routers (%d). Discarding this circuit.",
  1763. num_acceptable_routers);
  1764. return -1;
  1765. }
  1766. if (num_acceptable_routers < routelen) {
  1767. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  1768. routelen, num_acceptable_routers);
  1769. routelen = num_acceptable_routers;
  1770. }
  1771. return routelen;
  1772. }
  1773. /** Return a newly allocated list of uint16_t * for each predicted port not
  1774. * handled by a current circuit. */
  1775. static smartlist_t *
  1776. circuit_get_unhandled_ports(time_t now)
  1777. {
  1778. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1779. circuit_remove_handled_ports(dest);
  1780. return dest;
  1781. }
  1782. /** Return 1 if we already have circuits present or on the way for
  1783. * all anticipated ports. Return 0 if we should make more.
  1784. *
  1785. * If we're returning 0, set need_uptime and need_capacity to
  1786. * indicate any requirements that the unhandled ports have.
  1787. */
  1788. int
  1789. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1790. int *need_capacity)
  1791. {
  1792. int i, enough;
  1793. uint16_t *port;
  1794. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1795. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1796. tor_assert(need_uptime);
  1797. tor_assert(need_capacity);
  1798. // Always predict need_capacity
  1799. *need_capacity = 1;
  1800. enough = (smartlist_len(sl) == 0);
  1801. for (i = 0; i < smartlist_len(sl); ++i) {
  1802. port = smartlist_get(sl, i);
  1803. if (smartlist_string_num_isin(LongLivedServices, *port))
  1804. *need_uptime = 1;
  1805. tor_free(port);
  1806. }
  1807. smartlist_free(sl);
  1808. return enough;
  1809. }
  1810. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1811. * <b>needed_ports</b>, else return 0.
  1812. */
  1813. static int
  1814. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1815. { /* XXXX MOVE */
  1816. int i;
  1817. uint16_t port;
  1818. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1819. addr_policy_result_t r;
  1820. /* alignment issues aren't a worry for this dereference, since
  1821. needed_ports is explicitly a smartlist of uint16_t's */
  1822. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1823. tor_assert(port);
  1824. if (node)
  1825. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1826. else
  1827. continue;
  1828. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1829. return 1;
  1830. }
  1831. return 0;
  1832. }
  1833. /** Return true iff <b>conn</b> needs another general circuit to be
  1834. * built. */
  1835. static int
  1836. ap_stream_wants_exit_attention(connection_t *conn)
  1837. {
  1838. entry_connection_t *entry;
  1839. if (conn->type != CONN_TYPE_AP)
  1840. return 0;
  1841. entry = TO_ENTRY_CONN(conn);
  1842. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1843. !conn->marked_for_close &&
  1844. !(entry->want_onehop) && /* ignore one-hop streams */
  1845. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1846. !(entry->chosen_exit_name) && /* ignore defined streams */
  1847. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1848. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1849. MIN_CIRCUITS_HANDLING_STREAM))
  1850. return 1;
  1851. return 0;
  1852. }
  1853. /** Return a pointer to a suitable router to be the exit node for the
  1854. * general-purpose circuit we're about to build.
  1855. *
  1856. * Look through the connection array, and choose a router that maximizes
  1857. * the number of pending streams that can exit from this router.
  1858. *
  1859. * Return NULL if we can't find any suitable routers.
  1860. */
  1861. static const node_t *
  1862. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1863. {
  1864. int *n_supported;
  1865. int n_pending_connections = 0;
  1866. smartlist_t *connections;
  1867. int best_support = -1;
  1868. int n_best_support=0;
  1869. const or_options_t *options = get_options();
  1870. const smartlist_t *the_nodes;
  1871. const node_t *node=NULL;
  1872. connections = get_connection_array();
  1873. /* Count how many connections are waiting for a circuit to be built.
  1874. * We use this for log messages now, but in the future we may depend on it.
  1875. */
  1876. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1877. {
  1878. if (ap_stream_wants_exit_attention(conn))
  1879. ++n_pending_connections;
  1880. });
  1881. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1882. // n_pending_connections);
  1883. /* Now we count, for each of the routers in the directory, how many
  1884. * of the pending connections could possibly exit from that
  1885. * router (n_supported[i]). (We can't be sure about cases where we
  1886. * don't know the IP address of the pending connection.)
  1887. *
  1888. * -1 means "Don't use this router at all."
  1889. */
  1890. the_nodes = nodelist_get_list();
  1891. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1892. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1893. const int i = node_sl_idx;
  1894. if (router_digest_is_me(node->identity)) {
  1895. n_supported[i] = -1;
  1896. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1897. /* XXX there's probably a reverse predecessor attack here, but
  1898. * it's slow. should we take this out? -RD
  1899. */
  1900. continue;
  1901. }
  1902. if (!node_has_descriptor(node)) {
  1903. n_supported[i] = -1;
  1904. continue;
  1905. }
  1906. if (!node->is_running || node->is_bad_exit) {
  1907. n_supported[i] = -1;
  1908. continue; /* skip routers that are known to be down or bad exits */
  1909. }
  1910. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1911. /* never pick a non-general node as a random exit. */
  1912. n_supported[i] = -1;
  1913. continue;
  1914. }
  1915. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1916. n_supported[i] = -1;
  1917. continue; /* user asked us not to use it, no matter what */
  1918. }
  1919. if (options->ExitNodes &&
  1920. !routerset_contains_node(options->ExitNodes, node)) {
  1921. n_supported[i] = -1;
  1922. continue; /* not one of our chosen exit nodes */
  1923. }
  1924. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1925. n_supported[i] = -1;
  1926. continue; /* skip routers that are not suitable. Don't worry if
  1927. * this makes us reject all the possible routers: if so,
  1928. * we'll retry later in this function with need_update and
  1929. * need_capacity set to 0. */
  1930. }
  1931. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1932. /* if it's invalid and we don't want it */
  1933. n_supported[i] = -1;
  1934. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1935. // router->nickname, i);
  1936. continue; /* skip invalid routers */
  1937. }
  1938. if (options->ExcludeSingleHopRelays &&
  1939. node_allows_single_hop_exits(node)) {
  1940. n_supported[i] = -1;
  1941. continue;
  1942. }
  1943. if (node_exit_policy_rejects_all(node)) {
  1944. n_supported[i] = -1;
  1945. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1946. // router->nickname, i);
  1947. continue; /* skip routers that reject all */
  1948. }
  1949. n_supported[i] = 0;
  1950. /* iterate over connections */
  1951. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1952. if (!ap_stream_wants_exit_attention(conn))
  1953. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1954. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1955. ++n_supported[i];
  1956. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1957. // router->nickname, i, n_supported[i]);
  1958. } else {
  1959. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1960. // router->nickname, i);
  1961. }
  1962. } SMARTLIST_FOREACH_END(conn);
  1963. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1964. /* Leave best_support at -1 if that's where it is, so we can
  1965. * distinguish it later. */
  1966. continue;
  1967. }
  1968. if (n_supported[i] > best_support) {
  1969. /* If this router is better than previous ones, remember its index
  1970. * and goodness, and start counting how many routers are this good. */
  1971. best_support = n_supported[i]; n_best_support=1;
  1972. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1973. // router->nickname);
  1974. } else if (n_supported[i] == best_support) {
  1975. /* If this router is _as good_ as the best one, just increment the
  1976. * count of equally good routers.*/
  1977. ++n_best_support;
  1978. }
  1979. } SMARTLIST_FOREACH_END(node);
  1980. log_info(LD_CIRC,
  1981. "Found %d servers that might support %d/%d pending connections.",
  1982. n_best_support, best_support >= 0 ? best_support : 0,
  1983. n_pending_connections);
  1984. /* If any routers definitely support any pending connections, choose one
  1985. * at random. */
  1986. if (best_support > 0) {
  1987. smartlist_t *supporting = smartlist_new();
  1988. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1989. if (n_supported[node_sl_idx] == best_support)
  1990. smartlist_add(supporting, (void*)node);
  1991. });
  1992. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1993. smartlist_free(supporting);
  1994. } else {
  1995. /* Either there are no pending connections, or no routers even seem to
  1996. * possibly support any of them. Choose a router at random that satisfies
  1997. * at least one predicted exit port. */
  1998. int attempt;
  1999. smartlist_t *needed_ports, *supporting;
  2000. if (best_support == -1) {
  2001. if (need_uptime || need_capacity) {
  2002. log_info(LD_CIRC,
  2003. "We couldn't find any live%s%s routers; falling back "
  2004. "to list of all routers.",
  2005. need_capacity?", fast":"",
  2006. need_uptime?", stable":"");
  2007. tor_free(n_supported);
  2008. return choose_good_exit_server_general(0, 0);
  2009. }
  2010. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2011. "choosing a doomed exit at random.",
  2012. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  2013. }
  2014. supporting = smartlist_new();
  2015. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2016. for (attempt = 0; attempt < 2; attempt++) {
  2017. /* try once to pick only from routers that satisfy a needed port,
  2018. * then if there are none, pick from any that support exiting. */
  2019. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2020. if (n_supported[node_sl_idx] != -1 &&
  2021. (attempt || node_handles_some_port(node, needed_ports))) {
  2022. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2023. // try, router->nickname);
  2024. smartlist_add(supporting, (void*)node);
  2025. }
  2026. } SMARTLIST_FOREACH_END(node);
  2027. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2028. if (node)
  2029. break;
  2030. smartlist_clear(supporting);
  2031. /* If we reach this point, we can't actually support any unhandled
  2032. * predicted ports, so clear all the remaining ones. */
  2033. if (smartlist_len(needed_ports))
  2034. rep_hist_remove_predicted_ports(needed_ports);
  2035. }
  2036. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2037. smartlist_free(needed_ports);
  2038. smartlist_free(supporting);
  2039. }
  2040. tor_free(n_supported);
  2041. if (node) {
  2042. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2043. return node;
  2044. }
  2045. if (options->ExitNodes) {
  2046. log_warn(LD_CIRC,
  2047. "No specified %sexit routers seem to be running: "
  2048. "can't choose an exit.",
  2049. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  2050. }
  2051. return NULL;
  2052. }
  2053. /** Return a pointer to a suitable router to be the exit node for the
  2054. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2055. * if no router is suitable).
  2056. *
  2057. * For general-purpose circuits, pass it off to
  2058. * choose_good_exit_server_general()
  2059. *
  2060. * For client-side rendezvous circuits, choose a random node, weighted
  2061. * toward the preferences in 'options'.
  2062. */
  2063. static const node_t *
  2064. choose_good_exit_server(uint8_t purpose,
  2065. int need_uptime, int need_capacity, int is_internal)
  2066. {
  2067. const or_options_t *options = get_options();
  2068. router_crn_flags_t flags = CRN_NEED_DESC;
  2069. if (need_uptime)
  2070. flags |= CRN_NEED_UPTIME;
  2071. if (need_capacity)
  2072. flags |= CRN_NEED_CAPACITY;
  2073. switch (purpose) {
  2074. case CIRCUIT_PURPOSE_C_GENERAL:
  2075. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2076. flags |= CRN_ALLOW_INVALID;
  2077. if (is_internal) /* pick it like a middle hop */
  2078. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2079. else
  2080. return choose_good_exit_server_general(need_uptime,need_capacity);
  2081. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2082. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  2083. flags |= CRN_ALLOW_INVALID;
  2084. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2085. }
  2086. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2087. tor_fragile_assert();
  2088. return NULL;
  2089. }
  2090. /** Log a warning if the user specified an exit for the circuit that
  2091. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2092. static void
  2093. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2094. {
  2095. const or_options_t *options = get_options();
  2096. routerset_t *rs = options->ExcludeNodes;
  2097. const char *description;
  2098. uint8_t purpose = circ->base_.purpose;
  2099. if (circ->build_state->onehop_tunnel)
  2100. return;
  2101. switch (purpose)
  2102. {
  2103. default:
  2104. case CIRCUIT_PURPOSE_OR:
  2105. case CIRCUIT_PURPOSE_INTRO_POINT:
  2106. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2107. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2108. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2109. (int)purpose,
  2110. circuit_purpose_to_string(purpose));
  2111. return;
  2112. case CIRCUIT_PURPOSE_C_GENERAL:
  2113. if (circ->build_state->is_internal)
  2114. return;
  2115. description = "requested exit node";
  2116. rs = options->ExcludeExitNodesUnion_;
  2117. break;
  2118. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2119. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2120. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2121. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2122. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2123. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2124. case CIRCUIT_PURPOSE_TESTING:
  2125. return;
  2126. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2127. case CIRCUIT_PURPOSE_C_REND_READY:
  2128. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2129. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2130. description = "chosen rendezvous point";
  2131. break;
  2132. case CIRCUIT_PURPOSE_CONTROLLER:
  2133. rs = options->ExcludeExitNodesUnion_;
  2134. description = "controller-selected circuit target";
  2135. break;
  2136. }
  2137. if (routerset_contains_extendinfo(rs, exit)) {
  2138. /* We should never get here if StrictNodes is set to 1. */
  2139. if (options->StrictNodes) {
  2140. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2141. "even though StrictNodes is set. Please report. "
  2142. "(Circuit purpose: %s)",
  2143. description, extend_info_describe(exit),
  2144. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2145. circuit_purpose_to_string(purpose));
  2146. } else {
  2147. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2148. "ExcludeNodes%s, because no better options were available. To "
  2149. "prevent this (and possibly break your Tor functionality), "
  2150. "set the StrictNodes configuration option. "
  2151. "(Circuit purpose: %s)",
  2152. description, extend_info_describe(exit),
  2153. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2154. circuit_purpose_to_string(purpose));
  2155. }
  2156. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2157. }
  2158. return;
  2159. }
  2160. /** Decide a suitable length for circ's cpath, and pick an exit
  2161. * router (or use <b>exit</b> if provided). Store these in the
  2162. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2163. static int
  2164. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2165. {
  2166. cpath_build_state_t *state = circ->build_state;
  2167. if (state->onehop_tunnel) {
  2168. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2169. state->desired_path_len = 1;
  2170. } else {
  2171. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  2172. if (r < 1) /* must be at least 1 */
  2173. return -1;
  2174. state->desired_path_len = r;
  2175. }
  2176. if (exit) { /* the circuit-builder pre-requested one */
  2177. warn_if_last_router_excluded(circ, exit);
  2178. log_info(LD_CIRC,"Using requested exit node '%s'",
  2179. extend_info_describe(exit));
  2180. exit = extend_info_dup(exit);
  2181. } else { /* we have to decide one */
  2182. const node_t *node =
  2183. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  2184. state->need_capacity, state->is_internal);
  2185. if (!node) {
  2186. log_warn(LD_CIRC,"failed to choose an exit server");
  2187. return -1;
  2188. }
  2189. exit = extend_info_from_node(node, 0);
  2190. tor_assert(exit);
  2191. }
  2192. state->chosen_exit = exit;
  2193. return 0;
  2194. }
  2195. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2196. * hop to the cpath reflecting this. Don't send the next extend cell --
  2197. * the caller will do this if it wants to.
  2198. */
  2199. int
  2200. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2201. {
  2202. cpath_build_state_t *state;
  2203. tor_assert(exit);
  2204. tor_assert(circ);
  2205. state = circ->build_state;
  2206. tor_assert(state);
  2207. extend_info_free(state->chosen_exit);
  2208. state->chosen_exit = extend_info_dup(exit);
  2209. ++circ->build_state->desired_path_len;
  2210. onion_append_hop(&circ->cpath, exit);
  2211. return 0;
  2212. }
  2213. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2214. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2215. * send the next extend cell to begin connecting to that hop.
  2216. */
  2217. int
  2218. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2219. {
  2220. int err_reason = 0;
  2221. warn_if_last_router_excluded(circ, exit);
  2222. circuit_append_new_exit(circ, exit);
  2223. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2224. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2225. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2226. extend_info_describe(exit));
  2227. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2228. return -1;
  2229. }
  2230. /* Set timestamp_dirty, so we can check it for path use bias */
  2231. if (!circ->base_.timestamp_dirty)
  2232. circ->base_.timestamp_dirty = time(NULL);
  2233. return 0;
  2234. }
  2235. /** Return the number of routers in <b>routers</b> that are currently up
  2236. * and available for building circuits through.
  2237. */
  2238. static int
  2239. count_acceptable_nodes(smartlist_t *nodes)
  2240. {
  2241. int num=0;
  2242. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2243. // log_debug(LD_CIRC,
  2244. // "Contemplating whether router %d (%s) is a new option.",
  2245. // i, r->nickname);
  2246. if (! node->is_running)
  2247. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2248. continue;
  2249. if (! node->is_valid)
  2250. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2251. continue;
  2252. if (! node_has_descriptor(node))
  2253. continue;
  2254. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2255. * allows this node in some places, then we're getting an inaccurate
  2256. * count. For now, be conservative and don't count it. But later we
  2257. * should try to be smarter. */
  2258. ++num;
  2259. } SMARTLIST_FOREACH_END(node);
  2260. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2261. return num;
  2262. }
  2263. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2264. * This function is used to extend cpath by another hop.
  2265. */
  2266. void
  2267. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2268. {
  2269. if (*head_ptr) {
  2270. new_hop->next = (*head_ptr);
  2271. new_hop->prev = (*head_ptr)->prev;
  2272. (*head_ptr)->prev->next = new_hop;
  2273. (*head_ptr)->prev = new_hop;
  2274. } else {
  2275. *head_ptr = new_hop;
  2276. new_hop->prev = new_hop->next = new_hop;
  2277. }
  2278. }
  2279. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2280. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2281. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2282. * circuit. In particular, make sure we don't pick the exit node or its
  2283. * family, and make sure we don't duplicate any previous nodes or their
  2284. * families. */
  2285. static const node_t *
  2286. choose_good_middle_server(uint8_t purpose,
  2287. cpath_build_state_t *state,
  2288. crypt_path_t *head,
  2289. int cur_len)
  2290. {
  2291. int i;
  2292. const node_t *r, *choice;
  2293. crypt_path_t *cpath;
  2294. smartlist_t *excluded;
  2295. const or_options_t *options = get_options();
  2296. router_crn_flags_t flags = CRN_NEED_DESC;
  2297. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2298. purpose <= CIRCUIT_PURPOSE_MAX_);
  2299. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2300. excluded = smartlist_new();
  2301. if ((r = build_state_get_exit_node(state))) {
  2302. nodelist_add_node_and_family(excluded, r);
  2303. }
  2304. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2305. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2306. nodelist_add_node_and_family(excluded, r);
  2307. }
  2308. }
  2309. if (state->need_uptime)
  2310. flags |= CRN_NEED_UPTIME;
  2311. if (state->need_capacity)
  2312. flags |= CRN_NEED_CAPACITY;
  2313. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2314. flags |= CRN_ALLOW_INVALID;
  2315. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2316. smartlist_free(excluded);
  2317. return choice;
  2318. }
  2319. /** Pick a good entry server for the circuit to be built according to
  2320. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2321. * router (if we're an OR), and respect firewall settings; if we're
  2322. * configured to use entry guards, return one.
  2323. *
  2324. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2325. * guard, not for any particular circuit.
  2326. */
  2327. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2328. const node_t *
  2329. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2330. {
  2331. const node_t *choice;
  2332. smartlist_t *excluded;
  2333. const or_options_t *options = get_options();
  2334. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2335. const node_t *node;
  2336. if (state && options->UseEntryGuards &&
  2337. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2338. /* This request is for an entry server to use for a regular circuit,
  2339. * and we use entry guard nodes. Just return one of the guard nodes. */
  2340. return choose_random_entry(state);
  2341. }
  2342. excluded = smartlist_new();
  2343. if (state && (node = build_state_get_exit_node(state))) {
  2344. /* Exclude the exit node from the state, if we have one. Also exclude its
  2345. * family. */
  2346. nodelist_add_node_and_family(excluded, node);
  2347. }
  2348. if (firewall_is_fascist_or()) {
  2349. /* Exclude all ORs that we can't reach through our firewall */
  2350. smartlist_t *nodes = nodelist_get_list();
  2351. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2352. if (!fascist_firewall_allows_node(node))
  2353. smartlist_add(excluded, (void*)node);
  2354. });
  2355. }
  2356. /* and exclude current entry guards and their families, if applicable */
  2357. if (options->UseEntryGuards) {
  2358. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2359. {
  2360. if ((node = node_get_by_id(entry->identity))) {
  2361. nodelist_add_node_and_family(excluded, node);
  2362. }
  2363. });
  2364. }
  2365. if (state) {
  2366. if (state->need_uptime)
  2367. flags |= CRN_NEED_UPTIME;
  2368. if (state->need_capacity)
  2369. flags |= CRN_NEED_CAPACITY;
  2370. }
  2371. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  2372. flags |= CRN_ALLOW_INVALID;
  2373. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2374. smartlist_free(excluded);
  2375. return choice;
  2376. }
  2377. /** Return the first non-open hop in cpath, or return NULL if all
  2378. * hops are open. */
  2379. static crypt_path_t *
  2380. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2381. {
  2382. crypt_path_t *hop = cpath;
  2383. do {
  2384. if (hop->state != CPATH_STATE_OPEN)
  2385. return hop;
  2386. hop = hop->next;
  2387. } while (hop != cpath);
  2388. return NULL;
  2389. }
  2390. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2391. * based on <b>state</b>. Append the hop info to head_ptr.
  2392. */
  2393. static int
  2394. onion_extend_cpath(origin_circuit_t *circ)
  2395. {
  2396. uint8_t purpose = circ->base_.purpose;
  2397. cpath_build_state_t *state = circ->build_state;
  2398. int cur_len = circuit_get_cpath_len(circ);
  2399. extend_info_t *info = NULL;
  2400. if (cur_len >= state->desired_path_len) {
  2401. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2402. state->desired_path_len);
  2403. return 1;
  2404. }
  2405. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2406. state->desired_path_len);
  2407. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2408. info = extend_info_dup(state->chosen_exit);
  2409. } else if (cur_len == 0) { /* picking first node */
  2410. const node_t *r = choose_good_entry_server(purpose, state);
  2411. if (r) {
  2412. /* If we're a client, use the preferred address rather than the
  2413. primary address, for potentially connecting to an IPv6 OR
  2414. port. */
  2415. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  2416. tor_assert(info);
  2417. }
  2418. } else {
  2419. const node_t *r =
  2420. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2421. if (r) {
  2422. info = extend_info_from_node(r, 0);
  2423. tor_assert(info);
  2424. }
  2425. }
  2426. if (!info) {
  2427. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2428. "this circuit.", cur_len);
  2429. return -1;
  2430. }
  2431. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2432. extend_info_describe(info),
  2433. cur_len+1, build_state_get_exit_nickname(state));
  2434. onion_append_hop(&circ->cpath, info);
  2435. extend_info_free(info);
  2436. return 0;
  2437. }
  2438. /** Create a new hop, annotate it with information about its
  2439. * corresponding router <b>choice</b>, and append it to the
  2440. * end of the cpath <b>head_ptr</b>. */
  2441. static int
  2442. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2443. {
  2444. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2445. /* link hop into the cpath, at the end. */
  2446. onion_append_to_cpath(head_ptr, hop);
  2447. hop->magic = CRYPT_PATH_MAGIC;
  2448. hop->state = CPATH_STATE_CLOSED;
  2449. hop->extend_info = extend_info_dup(choice);
  2450. hop->package_window = circuit_initial_package_window();
  2451. hop->deliver_window = CIRCWINDOW_START;
  2452. return 0;
  2453. }
  2454. /** Allocate a new extend_info object based on the various arguments. */
  2455. extend_info_t *
  2456. extend_info_new(const char *nickname, const char *digest,
  2457. crypto_pk_t *onion_key,
  2458. const tor_addr_t *addr, uint16_t port)
  2459. {
  2460. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2461. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2462. if (nickname)
  2463. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2464. if (onion_key)
  2465. info->onion_key = crypto_pk_dup_key(onion_key);
  2466. tor_addr_copy(&info->addr, addr);
  2467. info->port = port;
  2468. return info;
  2469. }
  2470. /** Allocate and return a new extend_info that can be used to build a
  2471. * circuit to or through the node <b>node</b>. Use the primary address
  2472. * of the node (i.e. its IPv4 address) unless
  2473. * <b>for_direct_connect</b> is true, in which case the preferred
  2474. * address is used instead. May return NULL if there is not enough
  2475. * info about <b>node</b> to extend to it--for example, if there is no
  2476. * routerinfo_t or microdesc_t.
  2477. **/
  2478. extend_info_t *
  2479. extend_info_from_node(const node_t *node, int for_direct_connect)
  2480. {
  2481. tor_addr_port_t ap;
  2482. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2483. return NULL;
  2484. if (for_direct_connect)
  2485. node_get_pref_orport(node, &ap);
  2486. else
  2487. node_get_prim_orport(node, &ap);
  2488. log_debug(LD_CIRC, "using %s for %s",
  2489. fmt_addrport(&ap.addr, ap.port),
  2490. node->ri ? node->ri->nickname : node->rs->nickname);
  2491. if (node->ri)
  2492. return extend_info_new(node->ri->nickname,
  2493. node->identity,
  2494. node->ri->onion_pkey,
  2495. &ap.addr,
  2496. ap.port);
  2497. else if (node->rs && node->md)
  2498. return extend_info_new(node->rs->nickname,
  2499. node->identity,
  2500. node->md->onion_pkey,
  2501. &ap.addr,
  2502. ap.port);
  2503. else
  2504. return NULL;
  2505. }
  2506. /** Release storage held by an extend_info_t struct. */
  2507. void
  2508. extend_info_free(extend_info_t *info)
  2509. {
  2510. if (!info)
  2511. return;
  2512. crypto_pk_free(info->onion_key);
  2513. tor_free(info);
  2514. }
  2515. /** Allocate and return a new extend_info_t with the same contents as
  2516. * <b>info</b>. */
  2517. extend_info_t *
  2518. extend_info_dup(extend_info_t *info)
  2519. {
  2520. extend_info_t *newinfo;
  2521. tor_assert(info);
  2522. newinfo = tor_malloc(sizeof(extend_info_t));
  2523. memcpy(newinfo, info, sizeof(extend_info_t));
  2524. if (info->onion_key)
  2525. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2526. else
  2527. newinfo->onion_key = NULL;
  2528. return newinfo;
  2529. }
  2530. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2531. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2532. * the chosen exit, return NULL.
  2533. */
  2534. const node_t *
  2535. build_state_get_exit_node(cpath_build_state_t *state)
  2536. {
  2537. if (!state || !state->chosen_exit)
  2538. return NULL;
  2539. return node_get_by_id(state->chosen_exit->identity_digest);
  2540. }
  2541. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2542. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2543. * chosen exit, return NULL.
  2544. */
  2545. const char *
  2546. build_state_get_exit_nickname(cpath_build_state_t *state)
  2547. {
  2548. if (!state || !state->chosen_exit)
  2549. return NULL;
  2550. return state->chosen_exit->nickname;
  2551. }