circuitbuild.c 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502
  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 "onion_tap.h"
  30. #include "onion_fast.h"
  31. #include "policies.h"
  32. #include "transports.h"
  33. #include "relay.h"
  34. #include "rephist.h"
  35. #include "router.h"
  36. #include "routerlist.h"
  37. #include "routerparse.h"
  38. #include "routerset.h"
  39. #include "crypto.h"
  40. #ifndef MIN
  41. #define MIN(a,b) ((a)<(b)?(a):(b))
  42. #endif
  43. /********* START VARIABLES **********/
  44. /** A global list of all circuits at this hop. */
  45. extern circuit_t *global_circuitlist;
  46. /********* END VARIABLES ************/
  47. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  48. uint16_t port,
  49. const char *id_digest);
  50. static int circuit_deliver_create_cell(circuit_t *circ,
  51. const create_cell_t *create_cell,
  52. int relayed);
  53. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  54. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  55. static int onion_extend_cpath(origin_circuit_t *circ);
  56. static int count_acceptable_nodes(smartlist_t *routers);
  57. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  58. static int entry_guard_inc_first_hop_count(entry_guard_t *guard);
  59. static void pathbias_count_success(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->n_chan_create_cell, and send it */
  434. tor_assert(circ->n_chan_create_cell);
  435. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  436. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  437. continue;
  438. }
  439. tor_free(circ->n_chan_create_cell);
  440. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  441. }
  442. }
  443. SMARTLIST_FOREACH_END(circ);
  444. smartlist_free(pending_circs);
  445. }
  446. /** Find a new circid that isn't currently in use on the circ->n_chan
  447. * for the outgoing
  448. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  449. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  450. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  451. * it. Return -1 if we failed to find a suitable circid, else return 0.
  452. */
  453. static int
  454. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  455. int relayed)
  456. {
  457. cell_t cell;
  458. circid_t id;
  459. int r;
  460. tor_assert(circ);
  461. tor_assert(circ->n_chan);
  462. tor_assert(create_cell);
  463. tor_assert(create_cell->cell_type == CELL_CREATE ||
  464. create_cell->cell_type == CELL_CREATE_FAST ||
  465. create_cell->cell_type == CELL_CREATE2);
  466. id = get_unique_circ_id_by_chan(circ->n_chan);
  467. if (!id) {
  468. log_warn(LD_CIRC,"failed to get unique circID.");
  469. return -1;
  470. }
  471. log_debug(LD_CIRC,"Chosen circID %u.", id);
  472. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  473. memset(&cell, 0, sizeof(cell_t));
  474. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  475. : create_cell_format(&cell, create_cell);
  476. if (r < 0) {
  477. log_warn(LD_CIRC,"Couldn't format create cell");
  478. return -1;
  479. }
  480. cell.circ_id = circ->n_circ_id;
  481. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  482. CELL_DIRECTION_OUT, 0);
  483. if (CIRCUIT_IS_ORIGIN(circ)) {
  484. /* mark it so it gets better rate limiting treatment. */
  485. channel_timestamp_client(circ->n_chan);
  486. }
  487. return 0;
  488. }
  489. /** We've decided to start our reachability testing. If all
  490. * is set, log this to the user. Return 1 if we did, or 0 if
  491. * we chose not to log anything. */
  492. int
  493. inform_testing_reachability(void)
  494. {
  495. char dirbuf[128];
  496. const routerinfo_t *me = router_get_my_routerinfo();
  497. if (!me)
  498. return 0;
  499. control_event_server_status(LOG_NOTICE,
  500. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  501. me->address, me->or_port);
  502. if (me->dir_port) {
  503. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  504. me->address, me->dir_port);
  505. control_event_server_status(LOG_NOTICE,
  506. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  507. me->address, me->dir_port);
  508. }
  509. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  510. "(this may take up to %d minutes -- look for log "
  511. "messages indicating success)",
  512. me->address, me->or_port,
  513. me->dir_port ? dirbuf : "",
  514. me->dir_port ? "are" : "is",
  515. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  516. return 1;
  517. }
  518. /** Return true iff we should send a create_fast cell to start building a given
  519. * circuit */
  520. static INLINE int
  521. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  522. {
  523. const or_options_t *options = get_options();
  524. tor_assert(circ->cpath);
  525. tor_assert(circ->cpath->extend_info);
  526. if (!circ->cpath->extend_info->onion_key)
  527. return 1; /* our hand is forced: only a create_fast will work. */
  528. if (!options->FastFirstHopPK)
  529. return 0; /* we prefer to avoid create_fast */
  530. if (public_server_mode(options)) {
  531. /* We're a server, and we know an onion key. We can choose.
  532. * Prefer to blend our circuit into the other circuits we are
  533. * creating on behalf of others. */
  534. return 0;
  535. }
  536. return 1;
  537. }
  538. /** Return true if <b>circ</b> is the type of circuit we want to count
  539. * timeouts from. In particular, we want it to have not completed yet
  540. * (already completing indicates we cannibalized it), and we want it to
  541. * have exactly three hops.
  542. */
  543. int
  544. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  545. {
  546. return !circ->has_opened
  547. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  548. }
  549. #ifdef CURVE25519_ENABLED
  550. /** Return true if the ntor handshake is enabled in the configuration, or if
  551. * it's been set to "auto" in the configuration and it's enabled in the
  552. * consensus. */
  553. static int
  554. circuits_can_use_ntor(void)
  555. {
  556. const or_options_t *options = get_options();
  557. if (options->UseNTorHandshake != -1)
  558. return options->UseNTorHandshake;
  559. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  560. }
  561. #endif
  562. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  563. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  564. * accordingly. */
  565. static void
  566. circuit_pick_create_handshake(uint8_t *cell_type_out,
  567. uint16_t *handshake_type_out,
  568. const extend_info_t *ei)
  569. {
  570. #ifdef CURVE25519_ENABLED
  571. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  572. CURVE25519_PUBKEY_LEN) &&
  573. circuits_can_use_ntor()) {
  574. *cell_type_out = CELL_CREATE2;
  575. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  576. return;
  577. }
  578. #else
  579. (void) ei;
  580. #endif
  581. *cell_type_out = CELL_CREATE;
  582. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  583. }
  584. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  585. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  586. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  587. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  588. * *<b>create_cell_type_out</b> accordingly. */
  589. static void
  590. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  591. uint8_t *create_cell_type_out,
  592. uint16_t *handshake_type_out,
  593. const node_t *node_prev,
  594. const extend_info_t *ei)
  595. {
  596. uint8_t t;
  597. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  598. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  599. * proxy for whether it can do extend2 cells; once a version that
  600. * handles extend2 cells is out, remove it. */
  601. if (node_prev &&
  602. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  603. (node_has_curve25519_onion_key(node_prev) ||
  604. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  605. *cell_type_out = RELAY_COMMAND_EXTEND2;
  606. *create_cell_type_out = CELL_CREATE2;
  607. } else {
  608. *cell_type_out = RELAY_COMMAND_EXTEND;
  609. *create_cell_type_out = CELL_CREATE;
  610. }
  611. }
  612. /** This is the backbone function for building circuits.
  613. *
  614. * If circ's first hop is closed, then we need to build a create
  615. * cell and send it forward.
  616. *
  617. * Otherwise, we need to build a relay extend cell and send it
  618. * forward.
  619. *
  620. * Return -reason if we want to tear down circ, else return 0.
  621. */
  622. int
  623. circuit_send_next_onion_skin(origin_circuit_t *circ)
  624. {
  625. crypt_path_t *hop;
  626. const node_t *node;
  627. tor_assert(circ);
  628. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  629. /* This is the first hop. */
  630. create_cell_t cc;
  631. int fast;
  632. int len;
  633. log_debug(LD_CIRC,"First skin; sending create cell.");
  634. memset(&cc, 0, sizeof(cc));
  635. if (circ->build_state->onehop_tunnel)
  636. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  637. else
  638. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  639. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  640. fast = should_use_create_fast_for_circuit(circ);
  641. if (!fast) {
  642. /* We are an OR and we know the right onion key: we should
  643. * send a create cell.
  644. */
  645. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  646. circ->cpath->extend_info);
  647. note_request("cell: create", 1);
  648. } else {
  649. /* We are not an OR, and we're building the first hop of a circuit to a
  650. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  651. * and a DH operation. */
  652. cc.cell_type = CELL_CREATE_FAST;
  653. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  654. note_request("cell: create fast", 1);
  655. }
  656. len = onion_skin_create(cc.handshake_type,
  657. circ->cpath->extend_info,
  658. &circ->cpath->handshake_state,
  659. cc.onionskin);
  660. if (len < 0) {
  661. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  662. return - END_CIRC_REASON_INTERNAL;
  663. }
  664. cc.handshake_len = len;
  665. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  666. return - END_CIRC_REASON_RESOURCELIMIT;
  667. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  668. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  669. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  670. fast ? "CREATE_FAST" : "CREATE",
  671. node ? node_describe(node) : "<unnamed>");
  672. } else {
  673. extend_cell_t ec;
  674. int len;
  675. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  676. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  677. log_debug(LD_CIRC,"starting to send subsequent skin.");
  678. hop = onion_next_hop_in_cpath(circ->cpath);
  679. memset(&ec, 0, sizeof(ec));
  680. if (!hop) {
  681. /* done building the circuit. whew. */
  682. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  683. if (circuit_timeout_want_to_count_circ(circ)) {
  684. struct timeval end;
  685. long timediff;
  686. tor_gettimeofday(&end);
  687. timediff = tv_mdiff(&circ->base_.timestamp_created, &end);
  688. /*
  689. * If the circuit build time is much greater than we would have cut
  690. * it off at, we probably had a suspend event along this codepath,
  691. * and we should discard the value.
  692. */
  693. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  694. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  695. "Assuming clock jump. Purpose %d (%s)", timediff,
  696. circ->base_.purpose,
  697. circuit_purpose_to_string(circ->base_.purpose));
  698. } else if (!circuit_build_times_disabled()) {
  699. /* Only count circuit times if the network is live */
  700. if (circuit_build_times_network_check_live(&circ_times)) {
  701. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  702. circuit_build_times_set_timeout(&circ_times);
  703. }
  704. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  705. circuit_build_times_network_circ_success(&circ_times);
  706. }
  707. }
  708. }
  709. log_info(LD_CIRC,"circuit built!");
  710. circuit_reset_failure_count(0);
  711. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  712. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  713. }
  714. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  715. const or_options_t *options = get_options();
  716. can_complete_circuit=1;
  717. /* FFFF Log a count of known routers here */
  718. log_notice(LD_GENERAL,
  719. "Tor has successfully opened a circuit. "
  720. "Looks like client functionality is working.");
  721. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  722. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  723. clear_broken_connection_map(1);
  724. if (server_mode(options) && !check_whether_orport_reachable()) {
  725. inform_testing_reachability();
  726. consider_testing_reachability(1, 1);
  727. }
  728. }
  729. pathbias_count_success(circ);
  730. circuit_rep_hist_note_result(circ);
  731. circuit_has_opened(circ); /* do other actions as necessary */
  732. /* We're done with measurement circuits here. Just close them */
  733. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  734. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  735. return 0;
  736. }
  737. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  738. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  739. return - END_CIRC_REASON_INTERNAL;
  740. }
  741. {
  742. const node_t *prev_node;
  743. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  744. circuit_pick_extend_handshake(&ec.cell_type,
  745. &ec.create_cell.cell_type,
  746. &ec.create_cell.handshake_type,
  747. prev_node,
  748. hop->extend_info);
  749. }
  750. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  751. ec.orport_ipv4.port = hop->extend_info->port;
  752. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  753. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  754. len = onion_skin_create(ec.create_cell.handshake_type,
  755. hop->extend_info,
  756. &hop->handshake_state,
  757. ec.create_cell.onionskin);
  758. if (len < 0) {
  759. log_warn(LD_CIRC,"onion_skin_create failed.");
  760. return - END_CIRC_REASON_INTERNAL;
  761. }
  762. ec.create_cell.handshake_len = len;
  763. log_info(LD_CIRC,"Sending extend relay cell.");
  764. note_request("cell: extend", 1);
  765. {
  766. uint8_t command = 0;
  767. uint16_t payload_len=0;
  768. uint8_t payload[RELAY_PAYLOAD_SIZE];
  769. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  770. log_warn(LD_CIRC,"Couldn't format extend cell");
  771. return -END_CIRC_REASON_INTERNAL;
  772. }
  773. /* send it to hop->prev, because it will transfer
  774. * it to a create cell and then send to hop */
  775. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  776. command,
  777. (char*)payload, payload_len,
  778. hop->prev) < 0)
  779. return 0; /* circuit is closed */
  780. }
  781. hop->state = CPATH_STATE_AWAITING_KEYS;
  782. }
  783. return 0;
  784. }
  785. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  786. * something has also gone wrong with our network: notify the user,
  787. * and abandon all not-yet-used circuits. */
  788. void
  789. circuit_note_clock_jumped(int seconds_elapsed)
  790. {
  791. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  792. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  793. "assuming established circuits no longer work.",
  794. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  795. seconds_elapsed >=0 ? "forward" : "backward");
  796. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  797. seconds_elapsed);
  798. can_complete_circuit=0; /* so it'll log when it works again */
  799. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  800. "CLOCK_JUMPED");
  801. circuit_mark_all_unused_circs();
  802. circuit_expire_all_dirty_circs();
  803. }
  804. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  805. * skin and identity digest for the next hop. If we're already connected,
  806. * pass the onion skin to the next hop using a create cell; otherwise
  807. * launch a new OR connection, and <b>circ</b> will notice when the
  808. * connection succeeds or fails.
  809. *
  810. * Return -1 if we want to warn and tear down the circuit, else return 0.
  811. */
  812. int
  813. circuit_extend(cell_t *cell, circuit_t *circ)
  814. {
  815. channel_t *n_chan;
  816. relay_header_t rh;
  817. extend_cell_t ec;
  818. const char *msg = NULL;
  819. int should_launch = 0;
  820. if (circ->n_chan) {
  821. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  822. "n_chan already set. Bug/attack. Closing.");
  823. return -1;
  824. }
  825. if (circ->n_hop) {
  826. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  827. "conn to next hop already launched. Bug/attack. Closing.");
  828. return -1;
  829. }
  830. if (!server_mode(get_options())) {
  831. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  832. "Got an extend cell, but running as a client. Closing.");
  833. return -1;
  834. }
  835. relay_header_unpack(&rh, cell->payload);
  836. if (extend_cell_parse(&ec, rh.command,
  837. cell->payload+RELAY_HEADER_SIZE,
  838. rh.length) < 0) {
  839. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  840. "Can't parse extend cell. Closing circuit.");
  841. return -1;
  842. }
  843. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  844. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  845. "Client asked me to extend to zero destination port or addr.");
  846. return -1;
  847. }
  848. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  849. !get_options()->ExtendAllowPrivateAddresses) {
  850. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  851. "Client asked me to extend to a private address");
  852. return -1;
  853. }
  854. /* Check if they asked us for 0000..0000. We support using
  855. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  856. * but we don't want to let people send us extend cells for empty
  857. * fingerprints -- a) because it opens the user up to a mitm attack,
  858. * and b) because it lets an attacker force the relay to hold open a
  859. * new TLS connection for each extend request. */
  860. if (tor_digest_is_zero((const char*)ec.node_id)) {
  861. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  862. "Client asked me to extend without specifying an id_digest.");
  863. return -1;
  864. }
  865. /* Next, check if we're being asked to connect to the hop that the
  866. * extend cell came from. There isn't any reason for that, and it can
  867. * assist circular-path attacks. */
  868. if (tor_memeq(ec.node_id,
  869. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  870. DIGEST_LEN)) {
  871. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  872. "Client asked me to extend back to the previous hop.");
  873. return -1;
  874. }
  875. n_chan = channel_get_for_extend((const char*)ec.node_id,
  876. &ec.orport_ipv4.addr,
  877. &msg,
  878. &should_launch);
  879. if (!n_chan) {
  880. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  881. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  882. msg?msg:"????");
  883. circ->n_hop = extend_info_new(NULL /*nickname*/,
  884. (const char*)ec.node_id,
  885. NULL /*onion_key*/,
  886. NULL /*curve25519_key*/,
  887. &ec.orport_ipv4.addr,
  888. ec.orport_ipv4.port);
  889. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  890. sizeof(ec.create_cell));
  891. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  892. if (should_launch) {
  893. /* we should try to open a connection */
  894. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  895. ec.orport_ipv4.port,
  896. (const char*)ec.node_id);
  897. if (!n_chan) {
  898. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  899. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  900. return 0;
  901. }
  902. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  903. }
  904. /* return success. The onion/circuit/etc will be taken care of
  905. * automatically (may already have been) whenever n_chan reaches
  906. * OR_CONN_STATE_OPEN.
  907. */
  908. return 0;
  909. }
  910. tor_assert(!circ->n_hop); /* Connection is already established. */
  911. circ->n_chan = n_chan;
  912. log_debug(LD_CIRC,
  913. "n_chan is %s",
  914. channel_get_canonical_remote_descr(n_chan));
  915. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  916. return -1;
  917. return 0;
  918. }
  919. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  920. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  921. * used as follows:
  922. * - 20 to initialize f_digest
  923. * - 20 to initialize b_digest
  924. * - 16 to key f_crypto
  925. * - 16 to key b_crypto
  926. *
  927. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  928. */
  929. int
  930. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  931. int reverse)
  932. {
  933. crypto_digest_t *tmp_digest;
  934. crypto_cipher_t *tmp_crypto;
  935. tor_assert(cpath);
  936. tor_assert(key_data);
  937. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  938. cpath->f_digest || cpath->b_digest));
  939. cpath->f_digest = crypto_digest_new();
  940. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  941. cpath->b_digest = crypto_digest_new();
  942. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  943. if (!(cpath->f_crypto =
  944. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  945. log_warn(LD_BUG,"Forward cipher initialization failed.");
  946. return -1;
  947. }
  948. if (!(cpath->b_crypto =
  949. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  950. log_warn(LD_BUG,"Backward cipher initialization failed.");
  951. return -1;
  952. }
  953. if (reverse) {
  954. tmp_digest = cpath->f_digest;
  955. cpath->f_digest = cpath->b_digest;
  956. cpath->b_digest = tmp_digest;
  957. tmp_crypto = cpath->f_crypto;
  958. cpath->f_crypto = cpath->b_crypto;
  959. cpath->b_crypto = tmp_crypto;
  960. }
  961. return 0;
  962. }
  963. /** The minimum number of first hop completions before we start
  964. * thinking about warning about path bias and dropping guards */
  965. static int
  966. pathbias_get_min_circs(const or_options_t *options)
  967. {
  968. #define DFLT_PATH_BIAS_MIN_CIRC 20
  969. if (options->PathBiasCircThreshold >= 5)
  970. return options->PathBiasCircThreshold;
  971. else
  972. return networkstatus_get_param(NULL, "pb_mincircs",
  973. DFLT_PATH_BIAS_MIN_CIRC,
  974. 5, INT32_MAX);
  975. }
  976. static double
  977. pathbias_get_notice_rate(const or_options_t *options)
  978. {
  979. #define DFLT_PATH_BIAS_NOTICE_PCT 40
  980. if (options->PathBiasNoticeRate >= 0.0)
  981. return options->PathBiasNoticeRate;
  982. else
  983. return networkstatus_get_param(NULL, "pb_noticepct",
  984. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  985. }
  986. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  987. double
  988. pathbias_get_disable_rate(const or_options_t *options)
  989. {
  990. // XXX: This needs tuning based on use + experimentation before we set it
  991. #define DFLT_PATH_BIAS_DISABLE_PCT 0
  992. if (options->PathBiasDisableRate >= 0.0)
  993. return options->PathBiasDisableRate;
  994. else
  995. return networkstatus_get_param(NULL, "pb_disablepct",
  996. DFLT_PATH_BIAS_DISABLE_PCT, 0, 100)/100.0;
  997. }
  998. static int
  999. pathbias_get_scale_threshold(const or_options_t *options)
  1000. {
  1001. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 200
  1002. if (options->PathBiasScaleThreshold >= 2)
  1003. return options->PathBiasScaleThreshold;
  1004. else
  1005. return networkstatus_get_param(NULL, "pb_scalecircs",
  1006. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  1007. INT32_MAX);
  1008. }
  1009. static int
  1010. pathbias_get_scale_factor(const or_options_t *options)
  1011. {
  1012. #define DFLT_PATH_BIAS_SCALE_FACTOR 2
  1013. if (options->PathBiasScaleFactor >= 1)
  1014. return options->PathBiasScaleFactor;
  1015. else
  1016. return networkstatus_get_param(NULL, "pb_scalefactor",
  1017. DFLT_PATH_BIAS_SCALE_FACTOR, 1, INT32_MAX);
  1018. }
  1019. static const char *
  1020. pathbias_state_to_string(path_state_t state)
  1021. {
  1022. switch (state) {
  1023. case PATH_STATE_NEW_CIRC:
  1024. return "new";
  1025. case PATH_STATE_DID_FIRST_HOP:
  1026. return "first hop";
  1027. case PATH_STATE_SUCCEEDED:
  1028. return "succeeded";
  1029. }
  1030. return "unknown";
  1031. }
  1032. /**
  1033. * Check our circuit state to see if this is a successful first hop.
  1034. * If so, record it in the current guard's path bias first_hop count.
  1035. *
  1036. * Also check for several potential error cases for bug #6475.
  1037. */
  1038. static int
  1039. pathbias_count_first_hop(origin_circuit_t *circ)
  1040. {
  1041. #define FIRST_HOP_NOTICE_INTERVAL (600)
  1042. static ratelim_t first_hop_notice_limit =
  1043. RATELIM_INIT(FIRST_HOP_NOTICE_INTERVAL);
  1044. char *rate_msg = NULL;
  1045. /* We can't do path bias accounting without entry guards.
  1046. * Testing and controller circuits also have no guards. */
  1047. if (get_options()->UseEntryGuards == 0 ||
  1048. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1049. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) {
  1050. return 0;
  1051. }
  1052. /* Completely ignore one hop circuits */
  1053. if (circ->build_state->onehop_tunnel ||
  1054. circ->build_state->desired_path_len == 1) {
  1055. /* Check for inconsistency */
  1056. if (circ->build_state->desired_path_len != 1 ||
  1057. !circ->build_state->onehop_tunnel) {
  1058. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1059. approx_time()))) {
  1060. log_notice(LD_BUG,
  1061. "One-hop circuit has length %d. Path state is %s. "
  1062. "Circuit is a %s currently %s.%s",
  1063. circ->build_state->desired_path_len,
  1064. pathbias_state_to_string(circ->path_state),
  1065. circuit_purpose_to_string(circ->base_.purpose),
  1066. circuit_state_to_string(circ->base_.state),
  1067. rate_msg);
  1068. tor_free(rate_msg);
  1069. }
  1070. tor_fragile_assert();
  1071. }
  1072. return 0;
  1073. }
  1074. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1075. /* Help track down the real cause of bug #6475: */
  1076. if (circ->has_opened && circ->path_state != PATH_STATE_DID_FIRST_HOP) {
  1077. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1078. approx_time()))) {
  1079. log_info(LD_BUG,
  1080. "Opened circuit is in strange path state %s. "
  1081. "Circuit is a %s currently %s.%s",
  1082. pathbias_state_to_string(circ->path_state),
  1083. circuit_purpose_to_string(circ->base_.purpose),
  1084. circuit_state_to_string(circ->base_.state),
  1085. rate_msg);
  1086. tor_free(rate_msg);
  1087. }
  1088. }
  1089. /* Don't count cannibalized circs for path bias */
  1090. if (!circ->has_opened) {
  1091. entry_guard_t *guard;
  1092. guard =
  1093. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1094. if (guard) {
  1095. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1096. circ->path_state = PATH_STATE_DID_FIRST_HOP;
  1097. if (entry_guard_inc_first_hop_count(guard) < 0) {
  1098. /* Bogus guard; we already warned. */
  1099. return -END_CIRC_REASON_TORPROTOCOL;
  1100. }
  1101. } else {
  1102. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1103. approx_time()))) {
  1104. log_info(LD_BUG,
  1105. "Unopened circuit has strange path state %s. "
  1106. "Circuit is a %s currently %s.%s",
  1107. pathbias_state_to_string(circ->path_state),
  1108. circuit_purpose_to_string(circ->base_.purpose),
  1109. circuit_state_to_string(circ->base_.state),
  1110. rate_msg);
  1111. tor_free(rate_msg);
  1112. }
  1113. }
  1114. } else {
  1115. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1116. approx_time()))) {
  1117. log_info(LD_BUG,
  1118. "Unopened circuit has no known guard. "
  1119. "Circuit is a %s currently %s.%s",
  1120. circuit_purpose_to_string(circ->base_.purpose),
  1121. circuit_state_to_string(circ->base_.state),
  1122. rate_msg);
  1123. tor_free(rate_msg);
  1124. }
  1125. }
  1126. }
  1127. } else {
  1128. /* Help track down the real cause of bug #6475: */
  1129. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  1130. if ((rate_msg = rate_limit_log(&first_hop_notice_limit,
  1131. approx_time()))) {
  1132. log_info(LD_BUG,
  1133. "A %s circuit is in cpath state %d (opened: %d). "
  1134. "Circuit is a %s currently %s.%s",
  1135. pathbias_state_to_string(circ->path_state),
  1136. circ->cpath->state, circ->has_opened,
  1137. circuit_purpose_to_string(circ->base_.purpose),
  1138. circuit_state_to_string(circ->base_.state),
  1139. rate_msg);
  1140. tor_free(rate_msg);
  1141. }
  1142. }
  1143. }
  1144. return 0;
  1145. }
  1146. /**
  1147. * Check our circuit state to see if this is a successful circuit
  1148. * completion. If so, record it in the current guard's path bias
  1149. * success count.
  1150. *
  1151. * Also check for several potential error cases for bug #6475.
  1152. */
  1153. static void
  1154. pathbias_count_success(origin_circuit_t *circ)
  1155. {
  1156. #define SUCCESS_NOTICE_INTERVAL (600)
  1157. static ratelim_t success_notice_limit =
  1158. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  1159. char *rate_msg = NULL;
  1160. entry_guard_t *guard = NULL;
  1161. /* We can't do path bias accounting without entry guards.
  1162. * Testing and controller circuits also have no guards. */
  1163. if (get_options()->UseEntryGuards == 0 ||
  1164. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  1165. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) {
  1166. return;
  1167. }
  1168. /* Ignore one hop circuits */
  1169. if (circ->build_state->onehop_tunnel ||
  1170. circ->build_state->desired_path_len == 1) {
  1171. /* Check for consistency */
  1172. if (circ->build_state->desired_path_len != 1 ||
  1173. !circ->build_state->onehop_tunnel) {
  1174. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1175. approx_time()))) {
  1176. log_notice(LD_BUG,
  1177. "One-hop circuit has length %d. Path state is %s. "
  1178. "Circuit is a %s currently %s.%s",
  1179. circ->build_state->desired_path_len,
  1180. pathbias_state_to_string(circ->path_state),
  1181. circuit_purpose_to_string(circ->base_.purpose),
  1182. circuit_state_to_string(circ->base_.state),
  1183. rate_msg);
  1184. tor_free(rate_msg);
  1185. }
  1186. tor_fragile_assert();
  1187. }
  1188. return;
  1189. }
  1190. /* Don't count cannibalized/reused circs for path bias */
  1191. if (!circ->has_opened) {
  1192. guard =
  1193. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  1194. if (guard) {
  1195. if (circ->path_state == PATH_STATE_DID_FIRST_HOP) {
  1196. circ->path_state = PATH_STATE_SUCCEEDED;
  1197. guard->circuit_successes++;
  1198. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
  1199. guard->circuit_successes, guard->first_hops,
  1200. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1201. } else {
  1202. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1203. approx_time()))) {
  1204. log_info(LD_BUG,
  1205. "Succeeded circuit is in strange path state %s. "
  1206. "Circuit is a %s currently %s.%s",
  1207. pathbias_state_to_string(circ->path_state),
  1208. circuit_purpose_to_string(circ->base_.purpose),
  1209. circuit_state_to_string(circ->base_.state),
  1210. rate_msg);
  1211. tor_free(rate_msg);
  1212. }
  1213. }
  1214. if (guard->first_hops < guard->circuit_successes) {
  1215. log_notice(LD_BUG, "Unexpectedly high circuit_successes (%u/%u) "
  1216. "for guard %s=%s",
  1217. guard->circuit_successes, guard->first_hops,
  1218. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  1219. }
  1220. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1221. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1222. * No need to log that case. */
  1223. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1224. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1225. approx_time()))) {
  1226. log_info(LD_BUG,
  1227. "Completed circuit has no known guard. "
  1228. "Circuit is a %s currently %s.%s",
  1229. circuit_purpose_to_string(circ->base_.purpose),
  1230. circuit_state_to_string(circ->base_.state),
  1231. rate_msg);
  1232. tor_free(rate_msg);
  1233. }
  1234. }
  1235. } else {
  1236. if (circ->path_state != PATH_STATE_SUCCEEDED) {
  1237. if ((rate_msg = rate_limit_log(&success_notice_limit,
  1238. approx_time()))) {
  1239. log_info(LD_BUG,
  1240. "Opened circuit is in strange path state %s. "
  1241. "Circuit is a %s currently %s.%s",
  1242. pathbias_state_to_string(circ->path_state),
  1243. circuit_purpose_to_string(circ->base_.purpose),
  1244. circuit_state_to_string(circ->base_.state),
  1245. rate_msg);
  1246. tor_free(rate_msg);
  1247. }
  1248. }
  1249. }
  1250. }
  1251. /** Increment the number of times we successfully extended a circuit to
  1252. * 'guard', first checking if the failure rate is high enough that we should
  1253. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  1254. * guard looks fine. */
  1255. static int
  1256. entry_guard_inc_first_hop_count(entry_guard_t *guard)
  1257. {
  1258. const or_options_t *options = get_options();
  1259. entry_guards_changed();
  1260. if (guard->first_hops > (unsigned)pathbias_get_min_circs(options)) {
  1261. /* Note: We rely on the < comparison here to allow us to set a 0
  1262. * rate and disable the feature entirely. If refactoring, don't
  1263. * change to <= */
  1264. if (guard->circuit_successes/((double)guard->first_hops)
  1265. < pathbias_get_disable_rate(options)) {
  1266. /* This message is currently disabled by default. */
  1267. log_warn(LD_PROTOCOL,
  1268. "Extremely low circuit success rate %u/%u for guard %s=%s. "
  1269. "This indicates either an overloaded guard, an attack, or "
  1270. "a bug.",
  1271. guard->circuit_successes, guard->first_hops, guard->nickname,
  1272. hex_str(guard->identity, DIGEST_LEN));
  1273. guard->path_bias_disabled = 1;
  1274. guard->bad_since = approx_time();
  1275. return -1;
  1276. } else if (guard->circuit_successes/((double)guard->first_hops)
  1277. < pathbias_get_notice_rate(options)
  1278. && !guard->path_bias_notice) {
  1279. guard->path_bias_notice = 1;
  1280. log_notice(LD_PROTOCOL,
  1281. "Low circuit success rate %u/%u for guard %s=%s.",
  1282. guard->circuit_successes, guard->first_hops, guard->nickname,
  1283. hex_str(guard->identity, DIGEST_LEN));
  1284. }
  1285. }
  1286. /* If we get a ton of circuits, just scale everything down */
  1287. if (guard->first_hops > (unsigned)pathbias_get_scale_threshold(options)) {
  1288. const int scale_factor = pathbias_get_scale_factor(options);
  1289. /* For now, only scale if there will be no rounding error...
  1290. * XXX024: We want to switch to a real moving average for 0.2.4. */
  1291. if ((guard->first_hops % scale_factor) == 0 &&
  1292. (guard->circuit_successes % scale_factor) == 0) {
  1293. log_info(LD_PROTOCOL,
  1294. "Scaling pathbias counts to (%u/%u)/%d for guard %s=%s",
  1295. guard->circuit_successes, guard->first_hops,
  1296. scale_factor, guard->nickname, hex_str(guard->identity,
  1297. DIGEST_LEN));
  1298. guard->first_hops /= scale_factor;
  1299. guard->circuit_successes /= scale_factor;
  1300. }
  1301. }
  1302. guard->first_hops++;
  1303. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
  1304. guard->circuit_successes, guard->first_hops, guard->nickname,
  1305. hex_str(guard->identity, DIGEST_LEN));
  1306. return 0;
  1307. }
  1308. /** A created or extended cell came back to us on the circuit, and it included
  1309. * reply_cell as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  1310. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  1311. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  1312. *
  1313. * Calculate the appropriate keys and digests, make sure KH is
  1314. * correct, and initialize this hop of the cpath.
  1315. *
  1316. * Return - reason if we want to mark circ for close, else return 0.
  1317. */
  1318. int
  1319. circuit_finish_handshake(origin_circuit_t *circ,
  1320. const created_cell_t *reply)
  1321. {
  1322. char keys[CPATH_KEY_MATERIAL_LEN];
  1323. crypt_path_t *hop;
  1324. int rv;
  1325. if ((rv = pathbias_count_first_hop(circ)) < 0)
  1326. return rv;
  1327. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1328. hop = circ->cpath;
  1329. } else {
  1330. hop = onion_next_hop_in_cpath(circ->cpath);
  1331. if (!hop) { /* got an extended when we're all done? */
  1332. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1333. return - END_CIRC_REASON_TORPROTOCOL;
  1334. }
  1335. }
  1336. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1337. {
  1338. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1339. &hop->handshake_state,
  1340. reply->reply, reply->handshake_len,
  1341. (uint8_t*)keys, sizeof(keys),
  1342. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1343. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1344. return -END_CIRC_REASON_TORPROTOCOL;
  1345. }
  1346. }
  1347. onion_handshake_state_release(&hop->handshake_state);
  1348. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1349. return -END_CIRC_REASON_TORPROTOCOL;
  1350. }
  1351. hop->state = CPATH_STATE_OPEN;
  1352. log_info(LD_CIRC,"Finished building circuit hop:");
  1353. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1354. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1355. return 0;
  1356. }
  1357. /** We received a relay truncated cell on circ.
  1358. *
  1359. * Since we don't ask for truncates currently, getting a truncated
  1360. * means that a connection broke or an extend failed. For now,
  1361. * just give up: for circ to close, and return 0.
  1362. */
  1363. int
  1364. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1365. {
  1366. // crypt_path_t *victim;
  1367. // connection_t *stream;
  1368. tor_assert(circ);
  1369. tor_assert(layer);
  1370. /* XXX Since we don't ask for truncates currently, getting a truncated
  1371. * means that a connection broke or an extend failed. For now,
  1372. * just give up.
  1373. */
  1374. circuit_mark_for_close(TO_CIRCUIT(circ),
  1375. END_CIRC_REASON_FLAG_REMOTE|reason);
  1376. return 0;
  1377. #if 0
  1378. while (layer->next != circ->cpath) {
  1379. /* we need to clear out layer->next */
  1380. victim = layer->next;
  1381. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1382. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1383. if (stream->cpath_layer == victim) {
  1384. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1385. stream->stream_id);
  1386. /* no need to send 'end' relay cells,
  1387. * because the other side's already dead
  1388. */
  1389. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1390. }
  1391. }
  1392. layer->next = victim->next;
  1393. circuit_free_cpath_node(victim);
  1394. }
  1395. log_info(LD_CIRC, "finished");
  1396. return 0;
  1397. #endif
  1398. }
  1399. /** Given a response payload and keys, initialize, then send a created
  1400. * cell back.
  1401. */
  1402. int
  1403. onionskin_answer(or_circuit_t *circ,
  1404. const created_cell_t *created_cell,
  1405. const char *keys,
  1406. const uint8_t *rend_circ_nonce)
  1407. {
  1408. cell_t cell;
  1409. crypt_path_t *tmp_cpath;
  1410. if (created_cell_format(&cell, created_cell) < 0) {
  1411. log_warn(LD_BUG,"couldn't format created cell");
  1412. return -1;
  1413. }
  1414. cell.circ_id = circ->p_circ_id;
  1415. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1416. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1417. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1418. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1419. (unsigned int)get_uint32(keys),
  1420. (unsigned int)get_uint32(keys+20));
  1421. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1422. log_warn(LD_BUG,"Circuit initialization failed");
  1423. tor_free(tmp_cpath);
  1424. return -1;
  1425. }
  1426. circ->n_digest = tmp_cpath->f_digest;
  1427. circ->n_crypto = tmp_cpath->f_crypto;
  1428. circ->p_digest = tmp_cpath->b_digest;
  1429. circ->p_crypto = tmp_cpath->b_crypto;
  1430. tmp_cpath->magic = 0;
  1431. tor_free(tmp_cpath);
  1432. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1433. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1434. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1435. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1436. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1437. circ->is_first_hop ? "created_fast" : "created");
  1438. if (!channel_is_local(circ->p_chan) &&
  1439. !channel_is_outgoing(circ->p_chan)) {
  1440. /* record that we could process create cells from a non-local conn
  1441. * that we didn't initiate; presumably this means that create cells
  1442. * can reach us too. */
  1443. router_orport_found_reachable();
  1444. }
  1445. return 0;
  1446. }
  1447. /** Choose a length for a circuit of purpose <b>purpose</b>.
  1448. * Default length is 3 + the number of endpoints that would give something
  1449. * away. If the routerlist <b>routers</b> doesn't have enough routers
  1450. * to handle the desired path length, return as large a path length as
  1451. * is feasible, except if it's less than 2, in which case return -1.
  1452. */
  1453. static int
  1454. new_route_len(uint8_t purpose, extend_info_t *exit,
  1455. smartlist_t *nodes)
  1456. {
  1457. int num_acceptable_routers;
  1458. int routelen;
  1459. tor_assert(nodes);
  1460. routelen = DEFAULT_ROUTE_LEN;
  1461. if (exit &&
  1462. purpose != CIRCUIT_PURPOSE_TESTING &&
  1463. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1464. routelen++;
  1465. num_acceptable_routers = count_acceptable_nodes(nodes);
  1466. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1467. routelen, num_acceptable_routers, smartlist_len(nodes));
  1468. if (num_acceptable_routers < 2) {
  1469. log_info(LD_CIRC,
  1470. "Not enough acceptable routers (%d). Discarding this circuit.",
  1471. num_acceptable_routers);
  1472. return -1;
  1473. }
  1474. if (num_acceptable_routers < routelen) {
  1475. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  1476. routelen, num_acceptable_routers);
  1477. routelen = num_acceptable_routers;
  1478. }
  1479. return routelen;
  1480. }
  1481. /** Return a newly allocated list of uint16_t * for each predicted port not
  1482. * handled by a current circuit. */
  1483. static smartlist_t *
  1484. circuit_get_unhandled_ports(time_t now)
  1485. {
  1486. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1487. circuit_remove_handled_ports(dest);
  1488. return dest;
  1489. }
  1490. /** Return 1 if we already have circuits present or on the way for
  1491. * all anticipated ports. Return 0 if we should make more.
  1492. *
  1493. * If we're returning 0, set need_uptime and need_capacity to
  1494. * indicate any requirements that the unhandled ports have.
  1495. */
  1496. int
  1497. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1498. int *need_capacity)
  1499. {
  1500. int i, enough;
  1501. uint16_t *port;
  1502. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1503. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1504. tor_assert(need_uptime);
  1505. tor_assert(need_capacity);
  1506. // Always predict need_capacity
  1507. *need_capacity = 1;
  1508. enough = (smartlist_len(sl) == 0);
  1509. for (i = 0; i < smartlist_len(sl); ++i) {
  1510. port = smartlist_get(sl, i);
  1511. if (smartlist_string_num_isin(LongLivedServices, *port))
  1512. *need_uptime = 1;
  1513. tor_free(port);
  1514. }
  1515. smartlist_free(sl);
  1516. return enough;
  1517. }
  1518. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1519. * <b>needed_ports</b>, else return 0.
  1520. */
  1521. static int
  1522. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1523. { /* XXXX MOVE */
  1524. int i;
  1525. uint16_t port;
  1526. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1527. addr_policy_result_t r;
  1528. /* alignment issues aren't a worry for this dereference, since
  1529. needed_ports is explicitly a smartlist of uint16_t's */
  1530. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1531. tor_assert(port);
  1532. if (node)
  1533. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1534. else
  1535. continue;
  1536. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1537. return 1;
  1538. }
  1539. return 0;
  1540. }
  1541. /** Return true iff <b>conn</b> needs another general circuit to be
  1542. * built. */
  1543. static int
  1544. ap_stream_wants_exit_attention(connection_t *conn)
  1545. {
  1546. entry_connection_t *entry;
  1547. if (conn->type != CONN_TYPE_AP)
  1548. return 0;
  1549. entry = TO_ENTRY_CONN(conn);
  1550. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1551. !conn->marked_for_close &&
  1552. !(entry->want_onehop) && /* ignore one-hop streams */
  1553. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1554. !(entry->chosen_exit_name) && /* ignore defined streams */
  1555. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1556. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1557. MIN_CIRCUITS_HANDLING_STREAM))
  1558. return 1;
  1559. return 0;
  1560. }
  1561. /** Return a pointer to a suitable router to be the exit node for the
  1562. * general-purpose circuit we're about to build.
  1563. *
  1564. * Look through the connection array, and choose a router that maximizes
  1565. * the number of pending streams that can exit from this router.
  1566. *
  1567. * Return NULL if we can't find any suitable routers.
  1568. */
  1569. static const node_t *
  1570. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1571. {
  1572. int *n_supported;
  1573. int n_pending_connections = 0;
  1574. smartlist_t *connections;
  1575. int best_support = -1;
  1576. int n_best_support=0;
  1577. const or_options_t *options = get_options();
  1578. const smartlist_t *the_nodes;
  1579. const node_t *node=NULL;
  1580. connections = get_connection_array();
  1581. /* Count how many connections are waiting for a circuit to be built.
  1582. * We use this for log messages now, but in the future we may depend on it.
  1583. */
  1584. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1585. {
  1586. if (ap_stream_wants_exit_attention(conn))
  1587. ++n_pending_connections;
  1588. });
  1589. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1590. // n_pending_connections);
  1591. /* Now we count, for each of the routers in the directory, how many
  1592. * of the pending connections could possibly exit from that
  1593. * router (n_supported[i]). (We can't be sure about cases where we
  1594. * don't know the IP address of the pending connection.)
  1595. *
  1596. * -1 means "Don't use this router at all."
  1597. */
  1598. the_nodes = nodelist_get_list();
  1599. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1600. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1601. const int i = node_sl_idx;
  1602. if (router_digest_is_me(node->identity)) {
  1603. n_supported[i] = -1;
  1604. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1605. /* XXX there's probably a reverse predecessor attack here, but
  1606. * it's slow. should we take this out? -RD
  1607. */
  1608. continue;
  1609. }
  1610. if (!node_has_descriptor(node)) {
  1611. n_supported[i] = -1;
  1612. continue;
  1613. }
  1614. if (!node->is_running || node->is_bad_exit) {
  1615. n_supported[i] = -1;
  1616. continue; /* skip routers that are known to be down or bad exits */
  1617. }
  1618. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1619. /* never pick a non-general node as a random exit. */
  1620. n_supported[i] = -1;
  1621. continue;
  1622. }
  1623. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1624. n_supported[i] = -1;
  1625. continue; /* user asked us not to use it, no matter what */
  1626. }
  1627. if (options->ExitNodes &&
  1628. !routerset_contains_node(options->ExitNodes, node)) {
  1629. n_supported[i] = -1;
  1630. continue; /* not one of our chosen exit nodes */
  1631. }
  1632. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1633. n_supported[i] = -1;
  1634. continue; /* skip routers that are not suitable. Don't worry if
  1635. * this makes us reject all the possible routers: if so,
  1636. * we'll retry later in this function with need_update and
  1637. * need_capacity set to 0. */
  1638. }
  1639. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1640. /* if it's invalid and we don't want it */
  1641. n_supported[i] = -1;
  1642. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1643. // router->nickname, i);
  1644. continue; /* skip invalid routers */
  1645. }
  1646. if (options->ExcludeSingleHopRelays &&
  1647. node_allows_single_hop_exits(node)) {
  1648. n_supported[i] = -1;
  1649. continue;
  1650. }
  1651. if (node_exit_policy_rejects_all(node)) {
  1652. n_supported[i] = -1;
  1653. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1654. // router->nickname, i);
  1655. continue; /* skip routers that reject all */
  1656. }
  1657. n_supported[i] = 0;
  1658. /* iterate over connections */
  1659. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1660. if (!ap_stream_wants_exit_attention(conn))
  1661. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1662. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1663. ++n_supported[i];
  1664. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1665. // router->nickname, i, n_supported[i]);
  1666. } else {
  1667. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1668. // router->nickname, i);
  1669. }
  1670. } SMARTLIST_FOREACH_END(conn);
  1671. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1672. /* Leave best_support at -1 if that's where it is, so we can
  1673. * distinguish it later. */
  1674. continue;
  1675. }
  1676. if (n_supported[i] > best_support) {
  1677. /* If this router is better than previous ones, remember its index
  1678. * and goodness, and start counting how many routers are this good. */
  1679. best_support = n_supported[i]; n_best_support=1;
  1680. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1681. // router->nickname);
  1682. } else if (n_supported[i] == best_support) {
  1683. /* If this router is _as good_ as the best one, just increment the
  1684. * count of equally good routers.*/
  1685. ++n_best_support;
  1686. }
  1687. } SMARTLIST_FOREACH_END(node);
  1688. log_info(LD_CIRC,
  1689. "Found %d servers that might support %d/%d pending connections.",
  1690. n_best_support, best_support >= 0 ? best_support : 0,
  1691. n_pending_connections);
  1692. /* If any routers definitely support any pending connections, choose one
  1693. * at random. */
  1694. if (best_support > 0) {
  1695. smartlist_t *supporting = smartlist_new();
  1696. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1697. if (n_supported[node_sl_idx] == best_support)
  1698. smartlist_add(supporting, (void*)node);
  1699. });
  1700. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1701. smartlist_free(supporting);
  1702. } else {
  1703. /* Either there are no pending connections, or no routers even seem to
  1704. * possibly support any of them. Choose a router at random that satisfies
  1705. * at least one predicted exit port. */
  1706. int attempt;
  1707. smartlist_t *needed_ports, *supporting;
  1708. if (best_support == -1) {
  1709. if (need_uptime || need_capacity) {
  1710. log_info(LD_CIRC,
  1711. "We couldn't find any live%s%s routers; falling back "
  1712. "to list of all routers.",
  1713. need_capacity?", fast":"",
  1714. need_uptime?", stable":"");
  1715. tor_free(n_supported);
  1716. return choose_good_exit_server_general(0, 0);
  1717. }
  1718. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1719. "choosing a doomed exit at random.",
  1720. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1721. }
  1722. supporting = smartlist_new();
  1723. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1724. for (attempt = 0; attempt < 2; attempt++) {
  1725. /* try once to pick only from routers that satisfy a needed port,
  1726. * then if there are none, pick from any that support exiting. */
  1727. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1728. if (n_supported[node_sl_idx] != -1 &&
  1729. (attempt || node_handles_some_port(node, needed_ports))) {
  1730. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1731. // try, router->nickname);
  1732. smartlist_add(supporting, (void*)node);
  1733. }
  1734. } SMARTLIST_FOREACH_END(node);
  1735. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1736. if (node)
  1737. break;
  1738. smartlist_clear(supporting);
  1739. /* If we reach this point, we can't actually support any unhandled
  1740. * predicted ports, so clear all the remaining ones. */
  1741. if (smartlist_len(needed_ports))
  1742. rep_hist_remove_predicted_ports(needed_ports);
  1743. }
  1744. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1745. smartlist_free(needed_ports);
  1746. smartlist_free(supporting);
  1747. }
  1748. tor_free(n_supported);
  1749. if (node) {
  1750. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1751. return node;
  1752. }
  1753. if (options->ExitNodes) {
  1754. log_warn(LD_CIRC,
  1755. "No specified %sexit routers seem to be running: "
  1756. "can't choose an exit.",
  1757. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1758. }
  1759. return NULL;
  1760. }
  1761. /** Return a pointer to a suitable router to be the exit node for the
  1762. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1763. * if no router is suitable).
  1764. *
  1765. * For general-purpose circuits, pass it off to
  1766. * choose_good_exit_server_general()
  1767. *
  1768. * For client-side rendezvous circuits, choose a random node, weighted
  1769. * toward the preferences in 'options'.
  1770. */
  1771. static const node_t *
  1772. choose_good_exit_server(uint8_t purpose,
  1773. int need_uptime, int need_capacity, int is_internal)
  1774. {
  1775. const or_options_t *options = get_options();
  1776. router_crn_flags_t flags = CRN_NEED_DESC;
  1777. if (need_uptime)
  1778. flags |= CRN_NEED_UPTIME;
  1779. if (need_capacity)
  1780. flags |= CRN_NEED_CAPACITY;
  1781. switch (purpose) {
  1782. case CIRCUIT_PURPOSE_C_GENERAL:
  1783. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1784. flags |= CRN_ALLOW_INVALID;
  1785. if (is_internal) /* pick it like a middle hop */
  1786. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1787. else
  1788. return choose_good_exit_server_general(need_uptime,need_capacity);
  1789. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1790. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1791. flags |= CRN_ALLOW_INVALID;
  1792. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1793. }
  1794. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1795. tor_fragile_assert();
  1796. return NULL;
  1797. }
  1798. /** Log a warning if the user specified an exit for the circuit that
  1799. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1800. static void
  1801. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1802. {
  1803. const or_options_t *options = get_options();
  1804. routerset_t *rs = options->ExcludeNodes;
  1805. const char *description;
  1806. uint8_t purpose = circ->base_.purpose;
  1807. if (circ->build_state->onehop_tunnel)
  1808. return;
  1809. switch (purpose)
  1810. {
  1811. default:
  1812. case CIRCUIT_PURPOSE_OR:
  1813. case CIRCUIT_PURPOSE_INTRO_POINT:
  1814. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1815. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1816. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1817. (int)purpose,
  1818. circuit_purpose_to_string(purpose));
  1819. return;
  1820. case CIRCUIT_PURPOSE_C_GENERAL:
  1821. if (circ->build_state->is_internal)
  1822. return;
  1823. description = "requested exit node";
  1824. rs = options->ExcludeExitNodesUnion_;
  1825. break;
  1826. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1827. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1828. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1829. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1830. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1831. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1832. case CIRCUIT_PURPOSE_TESTING:
  1833. return;
  1834. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1835. case CIRCUIT_PURPOSE_C_REND_READY:
  1836. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1837. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1838. description = "chosen rendezvous point";
  1839. break;
  1840. case CIRCUIT_PURPOSE_CONTROLLER:
  1841. rs = options->ExcludeExitNodesUnion_;
  1842. description = "controller-selected circuit target";
  1843. break;
  1844. }
  1845. if (routerset_contains_extendinfo(rs, exit)) {
  1846. /* We should never get here if StrictNodes is set to 1. */
  1847. if (options->StrictNodes) {
  1848. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1849. "even though StrictNodes is set. Please report. "
  1850. "(Circuit purpose: %s)",
  1851. description, extend_info_describe(exit),
  1852. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1853. circuit_purpose_to_string(purpose));
  1854. } else {
  1855. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1856. "ExcludeNodes%s, because no better options were available. To "
  1857. "prevent this (and possibly break your Tor functionality), "
  1858. "set the StrictNodes configuration option. "
  1859. "(Circuit purpose: %s)",
  1860. description, extend_info_describe(exit),
  1861. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1862. circuit_purpose_to_string(purpose));
  1863. }
  1864. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1865. }
  1866. return;
  1867. }
  1868. /** Decide a suitable length for circ's cpath, and pick an exit
  1869. * router (or use <b>exit</b> if provided). Store these in the
  1870. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1871. static int
  1872. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1873. {
  1874. cpath_build_state_t *state = circ->build_state;
  1875. if (state->onehop_tunnel) {
  1876. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1877. state->desired_path_len = 1;
  1878. } else {
  1879. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1880. if (r < 1) /* must be at least 1 */
  1881. return -1;
  1882. state->desired_path_len = r;
  1883. }
  1884. if (exit) { /* the circuit-builder pre-requested one */
  1885. warn_if_last_router_excluded(circ, exit);
  1886. log_info(LD_CIRC,"Using requested exit node '%s'",
  1887. extend_info_describe(exit));
  1888. exit = extend_info_dup(exit);
  1889. } else { /* we have to decide one */
  1890. const node_t *node =
  1891. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1892. state->need_capacity, state->is_internal);
  1893. if (!node) {
  1894. log_warn(LD_CIRC,"failed to choose an exit server");
  1895. return -1;
  1896. }
  1897. exit = extend_info_from_node(node, 0);
  1898. tor_assert(exit);
  1899. }
  1900. state->chosen_exit = exit;
  1901. return 0;
  1902. }
  1903. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1904. * hop to the cpath reflecting this. Don't send the next extend cell --
  1905. * the caller will do this if it wants to.
  1906. */
  1907. int
  1908. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1909. {
  1910. cpath_build_state_t *state;
  1911. tor_assert(exit);
  1912. tor_assert(circ);
  1913. state = circ->build_state;
  1914. tor_assert(state);
  1915. extend_info_free(state->chosen_exit);
  1916. state->chosen_exit = extend_info_dup(exit);
  1917. ++circ->build_state->desired_path_len;
  1918. onion_append_hop(&circ->cpath, exit);
  1919. return 0;
  1920. }
  1921. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1922. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1923. * send the next extend cell to begin connecting to that hop.
  1924. */
  1925. int
  1926. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1927. {
  1928. int err_reason = 0;
  1929. warn_if_last_router_excluded(circ, exit);
  1930. circuit_append_new_exit(circ, exit);
  1931. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1932. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1933. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1934. extend_info_describe(exit));
  1935. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1936. return -1;
  1937. }
  1938. return 0;
  1939. }
  1940. /** Return the number of routers in <b>routers</b> that are currently up
  1941. * and available for building circuits through.
  1942. */
  1943. static int
  1944. count_acceptable_nodes(smartlist_t *nodes)
  1945. {
  1946. int num=0;
  1947. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1948. // log_debug(LD_CIRC,
  1949. // "Contemplating whether router %d (%s) is a new option.",
  1950. // i, r->nickname);
  1951. if (! node->is_running)
  1952. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1953. continue;
  1954. if (! node->is_valid)
  1955. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1956. continue;
  1957. if (! node_has_descriptor(node))
  1958. continue;
  1959. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1960. * allows this node in some places, then we're getting an inaccurate
  1961. * count. For now, be conservative and don't count it. But later we
  1962. * should try to be smarter. */
  1963. ++num;
  1964. } SMARTLIST_FOREACH_END(node);
  1965. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1966. return num;
  1967. }
  1968. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1969. * This function is used to extend cpath by another hop.
  1970. */
  1971. void
  1972. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1973. {
  1974. if (*head_ptr) {
  1975. new_hop->next = (*head_ptr);
  1976. new_hop->prev = (*head_ptr)->prev;
  1977. (*head_ptr)->prev->next = new_hop;
  1978. (*head_ptr)->prev = new_hop;
  1979. } else {
  1980. *head_ptr = new_hop;
  1981. new_hop->prev = new_hop->next = new_hop;
  1982. }
  1983. }
  1984. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1985. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1986. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1987. * circuit. In particular, make sure we don't pick the exit node or its
  1988. * family, and make sure we don't duplicate any previous nodes or their
  1989. * families. */
  1990. static const node_t *
  1991. choose_good_middle_server(uint8_t purpose,
  1992. cpath_build_state_t *state,
  1993. crypt_path_t *head,
  1994. int cur_len)
  1995. {
  1996. int i;
  1997. const node_t *r, *choice;
  1998. crypt_path_t *cpath;
  1999. smartlist_t *excluded;
  2000. const or_options_t *options = get_options();
  2001. router_crn_flags_t flags = CRN_NEED_DESC;
  2002. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  2003. purpose <= CIRCUIT_PURPOSE_MAX_);
  2004. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2005. excluded = smartlist_new();
  2006. if ((r = build_state_get_exit_node(state))) {
  2007. nodelist_add_node_and_family(excluded, r);
  2008. }
  2009. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2010. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2011. nodelist_add_node_and_family(excluded, r);
  2012. }
  2013. }
  2014. if (state->need_uptime)
  2015. flags |= CRN_NEED_UPTIME;
  2016. if (state->need_capacity)
  2017. flags |= CRN_NEED_CAPACITY;
  2018. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  2019. flags |= CRN_ALLOW_INVALID;
  2020. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2021. smartlist_free(excluded);
  2022. return choice;
  2023. }
  2024. /** Pick a good entry server for the circuit to be built according to
  2025. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2026. * router (if we're an OR), and respect firewall settings; if we're
  2027. * configured to use entry guards, return one.
  2028. *
  2029. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2030. * guard, not for any particular circuit.
  2031. */
  2032. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  2033. const node_t *
  2034. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2035. {
  2036. const node_t *choice;
  2037. smartlist_t *excluded;
  2038. const or_options_t *options = get_options();
  2039. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2040. const node_t *node;
  2041. if (state && options->UseEntryGuards &&
  2042. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2043. /* This request is for an entry server to use for a regular circuit,
  2044. * and we use entry guard nodes. Just return one of the guard nodes. */
  2045. return choose_random_entry(state);
  2046. }
  2047. excluded = smartlist_new();
  2048. if (state && (node = build_state_get_exit_node(state))) {
  2049. /* Exclude the exit node from the state, if we have one. Also exclude its
  2050. * family. */
  2051. nodelist_add_node_and_family(excluded, node);
  2052. }
  2053. if (firewall_is_fascist_or()) {
  2054. /* Exclude all ORs that we can't reach through our firewall */
  2055. smartlist_t *nodes = nodelist_get_list();
  2056. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2057. if (!fascist_firewall_allows_node(node))
  2058. smartlist_add(excluded, (void*)node);
  2059. });
  2060. }
  2061. /* and exclude current entry guards and their families, if applicable */
  2062. if (options->UseEntryGuards) {
  2063. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  2064. {
  2065. if ((node = node_get_by_id(entry->identity))) {
  2066. nodelist_add_node_and_family(excluded, node);
  2067. }
  2068. });
  2069. }
  2070. if (state) {
  2071. if (state->need_uptime)
  2072. flags |= CRN_NEED_UPTIME;
  2073. if (state->need_capacity)
  2074. flags |= CRN_NEED_CAPACITY;
  2075. }
  2076. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  2077. flags |= CRN_ALLOW_INVALID;
  2078. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2079. smartlist_free(excluded);
  2080. return choice;
  2081. }
  2082. /** Return the first non-open hop in cpath, or return NULL if all
  2083. * hops are open. */
  2084. static crypt_path_t *
  2085. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2086. {
  2087. crypt_path_t *hop = cpath;
  2088. do {
  2089. if (hop->state != CPATH_STATE_OPEN)
  2090. return hop;
  2091. hop = hop->next;
  2092. } while (hop != cpath);
  2093. return NULL;
  2094. }
  2095. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2096. * based on <b>state</b>. Append the hop info to head_ptr.
  2097. */
  2098. static int
  2099. onion_extend_cpath(origin_circuit_t *circ)
  2100. {
  2101. uint8_t purpose = circ->base_.purpose;
  2102. cpath_build_state_t *state = circ->build_state;
  2103. int cur_len = circuit_get_cpath_len(circ);
  2104. extend_info_t *info = NULL;
  2105. if (cur_len >= state->desired_path_len) {
  2106. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2107. state->desired_path_len);
  2108. return 1;
  2109. }
  2110. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2111. state->desired_path_len);
  2112. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2113. info = extend_info_dup(state->chosen_exit);
  2114. } else if (cur_len == 0) { /* picking first node */
  2115. const node_t *r = choose_good_entry_server(purpose, state);
  2116. if (r) {
  2117. /* If we're a client, use the preferred address rather than the
  2118. primary address, for potentially connecting to an IPv6 OR
  2119. port. */
  2120. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  2121. tor_assert(info);
  2122. }
  2123. } else {
  2124. const node_t *r =
  2125. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2126. if (r) {
  2127. info = extend_info_from_node(r, 0);
  2128. tor_assert(info);
  2129. }
  2130. }
  2131. if (!info) {
  2132. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2133. "this circuit.", cur_len);
  2134. return -1;
  2135. }
  2136. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2137. extend_info_describe(info),
  2138. cur_len+1, build_state_get_exit_nickname(state));
  2139. onion_append_hop(&circ->cpath, info);
  2140. extend_info_free(info);
  2141. return 0;
  2142. }
  2143. /** Create a new hop, annotate it with information about its
  2144. * corresponding router <b>choice</b>, and append it to the
  2145. * end of the cpath <b>head_ptr</b>. */
  2146. static int
  2147. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2148. {
  2149. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2150. /* link hop into the cpath, at the end. */
  2151. onion_append_to_cpath(head_ptr, hop);
  2152. hop->magic = CRYPT_PATH_MAGIC;
  2153. hop->state = CPATH_STATE_CLOSED;
  2154. hop->extend_info = extend_info_dup(choice);
  2155. hop->package_window = circuit_initial_package_window();
  2156. hop->deliver_window = CIRCWINDOW_START;
  2157. return 0;
  2158. }
  2159. /** Allocate a new extend_info object based on the various arguments. */
  2160. extend_info_t *
  2161. extend_info_new(const char *nickname, const char *digest,
  2162. crypto_pk_t *onion_key,
  2163. const curve25519_public_key_t *curve25519_key,
  2164. const tor_addr_t *addr, uint16_t port)
  2165. {
  2166. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2167. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2168. if (nickname)
  2169. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2170. if (onion_key)
  2171. info->onion_key = crypto_pk_dup_key(onion_key);
  2172. #ifdef CURVE25519_ENABLED
  2173. if (curve25519_key)
  2174. memcpy(&info->curve25519_onion_key, curve25519_key,
  2175. sizeof(curve25519_public_key_t));
  2176. #else
  2177. (void)curve25519_key;
  2178. #endif
  2179. tor_addr_copy(&info->addr, addr);
  2180. info->port = port;
  2181. return info;
  2182. }
  2183. /** Allocate and return a new extend_info that can be used to build a
  2184. * circuit to or through the node <b>node</b>. Use the primary address
  2185. * of the node (i.e. its IPv4 address) unless
  2186. * <b>for_direct_connect</b> is true, in which case the preferred
  2187. * address is used instead. May return NULL if there is not enough
  2188. * info about <b>node</b> to extend to it--for example, if there is no
  2189. * routerinfo_t or microdesc_t.
  2190. **/
  2191. extend_info_t *
  2192. extend_info_from_node(const node_t *node, int for_direct_connect)
  2193. {
  2194. tor_addr_port_t ap;
  2195. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  2196. return NULL;
  2197. if (for_direct_connect)
  2198. node_get_pref_orport(node, &ap);
  2199. else
  2200. node_get_prim_orport(node, &ap);
  2201. log_debug(LD_CIRC, "using %s for %s",
  2202. fmt_addrport(&ap.addr, ap.port),
  2203. node->ri ? node->ri->nickname : node->rs->nickname);
  2204. if (node->ri)
  2205. return extend_info_new(node->ri->nickname,
  2206. node->identity,
  2207. node->ri->onion_pkey,
  2208. node->ri->onion_curve25519_pkey,
  2209. &ap.addr,
  2210. ap.port);
  2211. else if (node->rs && node->md)
  2212. return extend_info_new(node->rs->nickname,
  2213. node->identity,
  2214. node->md->onion_pkey,
  2215. node->md->onion_curve25519_pkey,
  2216. &ap.addr,
  2217. ap.port);
  2218. else
  2219. return NULL;
  2220. }
  2221. /** Release storage held by an extend_info_t struct. */
  2222. void
  2223. extend_info_free(extend_info_t *info)
  2224. {
  2225. if (!info)
  2226. return;
  2227. crypto_pk_free(info->onion_key);
  2228. tor_free(info);
  2229. }
  2230. /** Allocate and return a new extend_info_t with the same contents as
  2231. * <b>info</b>. */
  2232. extend_info_t *
  2233. extend_info_dup(extend_info_t *info)
  2234. {
  2235. extend_info_t *newinfo;
  2236. tor_assert(info);
  2237. newinfo = tor_malloc(sizeof(extend_info_t));
  2238. memcpy(newinfo, info, sizeof(extend_info_t));
  2239. if (info->onion_key)
  2240. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2241. else
  2242. newinfo->onion_key = NULL;
  2243. return newinfo;
  2244. }
  2245. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2246. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2247. * the chosen exit, return NULL.
  2248. */
  2249. const node_t *
  2250. build_state_get_exit_node(cpath_build_state_t *state)
  2251. {
  2252. if (!state || !state->chosen_exit)
  2253. return NULL;
  2254. return node_get_by_id(state->chosen_exit->identity_digest);
  2255. }
  2256. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2257. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2258. * chosen exit, return NULL.
  2259. */
  2260. const char *
  2261. build_state_get_exit_nickname(cpath_build_state_t *state)
  2262. {
  2263. if (!state || !state->chosen_exit)
  2264. return NULL;
  2265. return state->chosen_exit->nickname;
  2266. }