circuitbuild.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char circuitbuild_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file circuitbuild.c
  10. * \brief The actual details of building circuits.
  11. **/
  12. #include "or.h"
  13. /********* START VARIABLES **********/
  14. /** A global list of all circuits at this hop. */
  15. extern circuit_t *global_circuitlist;
  16. /** An entry_guard_t represents our information about a chosen long-term
  17. * first hop, known as a "helper" node in the literature. We can't just
  18. * use a routerinfo_t, since we want to remember these even when we
  19. * don't have a directory. */
  20. typedef struct {
  21. char nickname[MAX_NICKNAME_LEN+1];
  22. char identity[DIGEST_LEN];
  23. unsigned int made_contact : 1; /**< 0 if we have never connected to this
  24. * router, 1 if we have. */
  25. unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
  26. * in spite of having it marked as unreachable?*/
  27. time_t bad_since; /**< 0 if this guard is currently usable, or the time at
  28. * which it was observed to become (according to the
  29. * directory or the user configuration) unusable. */
  30. time_t unreachable_since; /**< 0 if we can connect to this guard, or the
  31. * time at which we first noticed we couldn't
  32. * connect to it. */
  33. time_t last_attempted; /**< 0 if we can connect to this guard, or the time
  34. * at which we last failed to connect to it. */
  35. } entry_guard_t;
  36. /** A list of our chosen entry guards. */
  37. static smartlist_t *entry_guards = NULL;
  38. /** A value of 1 means that the entry_guards list has changed
  39. * and those changes need to be flushed to disk. */
  40. static int entry_guards_dirty = 0;
  41. /********* END VARIABLES ************/
  42. static int circuit_deliver_create_cell(circuit_t *circ,
  43. uint8_t cell_type, const char *payload);
  44. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  45. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  46. static int onion_extend_cpath(origin_circuit_t *circ);
  47. static int count_acceptable_routers(smartlist_t *routers);
  48. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  49. static routerinfo_t *choose_random_entry(cpath_build_state_t *state);
  50. static void entry_guards_changed(void);
  51. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  52. * and with the high bit specified by conn-\>circ_id_type, until we get
  53. * a circ_id that is not in use by any other circuit on that conn.
  54. *
  55. * Return it, or 0 if can't get a unique circ_id.
  56. */
  57. static uint16_t
  58. get_unique_circ_id_by_conn(or_connection_t *conn)
  59. {
  60. uint16_t test_circ_id;
  61. uint16_t attempts=0;
  62. uint16_t high_bit;
  63. tor_assert(conn);
  64. if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  65. log_warn(LD_BUG, "Bug: Trying to pick a circuit ID for a connection from "
  66. "a client with no identity.");
  67. return 0;
  68. }
  69. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  70. do {
  71. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  72. * circID such that (high_bit|test_circ_id) is not already used. */
  73. test_circ_id = conn->next_circ_id++;
  74. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  75. test_circ_id = 1;
  76. conn->next_circ_id = 2;
  77. }
  78. if (++attempts > 1<<15) {
  79. /* Make sure we don't loop forever if all circ_id's are used. This
  80. * matters because it's an external DoS opportunity.
  81. */
  82. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  83. return 0;
  84. }
  85. test_circ_id |= high_bit;
  86. } while (circuit_get_by_circid_orconn(test_circ_id, conn));
  87. return test_circ_id;
  88. }
  89. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  90. * the currently built elements of circuit_t. If <b>verbose</b> is true, also
  91. * list information about link status in a more verbose format using spaces.
  92. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  93. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  94. * names.
  95. */
  96. static char *
  97. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  98. {
  99. crypt_path_t *hop;
  100. smartlist_t *elements;
  101. const char *states[] = {"closed", "waiting for keys", "open"};
  102. char buf[128];
  103. char *s;
  104. elements = smartlist_create();
  105. if (verbose) {
  106. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  107. tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
  108. circ->build_state->is_internal ? "internal" : "exit",
  109. circ->build_state->need_uptime ? " (high-uptime)" : "",
  110. circ->build_state->desired_path_len,
  111. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
  112. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  113. (nickname?nickname:"*unnamed*"));
  114. smartlist_add(elements, tor_strdup(buf));
  115. }
  116. hop = circ->cpath;
  117. do {
  118. routerinfo_t *ri;
  119. char *elt;
  120. if (!hop)
  121. break;
  122. if (!verbose && hop->state != CPATH_STATE_OPEN)
  123. break;
  124. if (!hop->extend_info)
  125. break;
  126. if (verbose_names) {
  127. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  128. if ((ri = router_get_by_digest(hop->extend_info->identity_digest))) {
  129. router_get_verbose_nickname(elt, ri);
  130. } else if (hop->extend_info->nickname &&
  131. is_legal_nickname(hop->extend_info->nickname)) {
  132. elt[0] = '$';
  133. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  134. hop->extend_info->identity_digest, DIGEST_LEN);
  135. elt[HEX_DIGEST_LEN+1]= '~';
  136. strlcpy(elt+HEX_DIGEST_LEN+2,
  137. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  138. } else {
  139. elt[0] = '$';
  140. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  141. hop->extend_info->identity_digest, DIGEST_LEN);
  142. }
  143. } else { /* ! verbose_names */
  144. if ((ri = router_get_by_digest(hop->extend_info->identity_digest)) &&
  145. ri->is_named) {
  146. elt = tor_strdup(hop->extend_info->nickname);
  147. } else {
  148. elt = tor_malloc(HEX_DIGEST_LEN+2);
  149. elt[0] = '$';
  150. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  151. hop->extend_info->identity_digest, DIGEST_LEN);
  152. }
  153. }
  154. tor_assert(elt);
  155. if (verbose) {
  156. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  157. char *v = tor_malloc(len);
  158. tor_assert(hop->state <= 2);
  159. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  160. smartlist_add(elements, v);
  161. tor_free(elt);
  162. } else {
  163. smartlist_add(elements, elt);
  164. }
  165. hop = hop->next;
  166. } while (hop != circ->cpath);
  167. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  168. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  169. smartlist_free(elements);
  170. return s;
  171. }
  172. /** If <b>verbose</b> is false, allocate and return a comma-separated
  173. * list of the currently built elements of circuit_t. If
  174. * <b>verbose</b> is true, also list information about link status in
  175. * a more verbose format using spaces.
  176. */
  177. char *
  178. circuit_list_path(origin_circuit_t *circ, int verbose)
  179. {
  180. return circuit_list_path_impl(circ, verbose, 0);
  181. }
  182. /** Allocate and return a comma-separated list of the currently built elements
  183. * of circuit_t, giving each as a verbose nickname.
  184. */
  185. char *
  186. circuit_list_path_for_controller(origin_circuit_t *circ)
  187. {
  188. return circuit_list_path_impl(circ, 0, 1);
  189. }
  190. /** Log, at severity <b>severity</b>, the nicknames of each router in
  191. * circ's cpath. Also log the length of the cpath, and the intended
  192. * exit point.
  193. */
  194. void
  195. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  196. {
  197. char *s = circuit_list_path(circ,1);
  198. log(severity,domain,"%s",s);
  199. tor_free(s);
  200. }
  201. /** Tell the rep(utation)hist(ory) module about the status of the links
  202. * in circ. Hops that have become OPEN are marked as successfully
  203. * extended; the _first_ hop that isn't open (if any) is marked as
  204. * unable to extend.
  205. */
  206. /* XXXX Someday we should learn from OR circuits too. */
  207. void
  208. circuit_rep_hist_note_result(origin_circuit_t *circ)
  209. {
  210. crypt_path_t *hop;
  211. char *prev_digest = NULL;
  212. routerinfo_t *router;
  213. hop = circ->cpath;
  214. if (!hop) /* circuit hasn't started building yet. */
  215. return;
  216. if (server_mode(get_options())) {
  217. routerinfo_t *me = router_get_my_routerinfo();
  218. if (!me)
  219. return;
  220. prev_digest = me->cache_info.identity_digest;
  221. }
  222. do {
  223. router = router_get_by_digest(hop->extend_info->identity_digest);
  224. if (router) {
  225. if (prev_digest) {
  226. if (hop->state == CPATH_STATE_OPEN)
  227. rep_hist_note_extend_succeeded(prev_digest,
  228. router->cache_info.identity_digest);
  229. else {
  230. rep_hist_note_extend_failed(prev_digest,
  231. router->cache_info.identity_digest);
  232. break;
  233. }
  234. }
  235. prev_digest = router->cache_info.identity_digest;
  236. } else {
  237. prev_digest = NULL;
  238. }
  239. hop=hop->next;
  240. } while (hop!=circ->cpath);
  241. }
  242. /** Pick all the entries in our cpath. Stop and return 0 when we're
  243. * happy, or return -1 if an error occurs. */
  244. static int
  245. onion_populate_cpath(origin_circuit_t *circ)
  246. {
  247. int r;
  248. again:
  249. r = onion_extend_cpath(circ);
  250. if (r < 0) {
  251. log_info(LD_CIRC,"Generating cpath hop failed.");
  252. return -1;
  253. }
  254. if (r == 0)
  255. goto again;
  256. return 0; /* if r == 1 */
  257. }
  258. /** Create and return a new origin circuit. Initialize its purpose and
  259. * build-state based on our arguments. */
  260. origin_circuit_t *
  261. origin_circuit_init(uint8_t purpose, int onehop_tunnel,
  262. int need_uptime, int need_capacity, int internal)
  263. {
  264. /* sets circ->p_circ_id and circ->p_conn */
  265. origin_circuit_t *circ = origin_circuit_new();
  266. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  267. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  268. circ->build_state->onehop_tunnel = onehop_tunnel;
  269. circ->build_state->need_uptime = need_uptime;
  270. circ->build_state->need_capacity = need_capacity;
  271. circ->build_state->is_internal = internal;
  272. circ->_base.purpose = purpose;
  273. return circ;
  274. }
  275. /** Build a new circuit for <b>purpose</b>. If <b>info</b>
  276. * is defined, then use that as your exit router, else choose a suitable
  277. * exit node.
  278. *
  279. * Also launch a connection to the first OR in the chosen path, if
  280. * it's not open already.
  281. */
  282. origin_circuit_t *
  283. circuit_establish_circuit(uint8_t purpose, int onehop_tunnel,
  284. extend_info_t *info,
  285. int need_uptime, int need_capacity, int internal)
  286. {
  287. origin_circuit_t *circ;
  288. int err_reason = 0;
  289. circ = origin_circuit_init(purpose, onehop_tunnel,
  290. need_uptime, need_capacity, internal);
  291. if (onion_pick_cpath_exit(circ, info) < 0 ||
  292. onion_populate_cpath(circ) < 0) {
  293. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  294. return NULL;
  295. }
  296. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  297. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  298. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  299. return NULL;
  300. }
  301. return circ;
  302. }
  303. /** Start establishing the first hop of our circuit. Figure out what
  304. * OR we should connect to, and if necessary start the connection to
  305. * it. If we're already connected, then send the 'create' cell.
  306. * Return 0 for ok, -reason if circ should be marked-for-close. */
  307. int
  308. circuit_handle_first_hop(origin_circuit_t *circ)
  309. {
  310. crypt_path_t *firsthop;
  311. or_connection_t *n_conn;
  312. char tmpbuf[INET_NTOA_BUF_LEN];
  313. struct in_addr in;
  314. int err_reason = 0;
  315. firsthop = onion_next_hop_in_cpath(circ->cpath);
  316. tor_assert(firsthop);
  317. tor_assert(firsthop->extend_info);
  318. /* now see if we're already connected to the first OR in 'route' */
  319. in.s_addr = htonl(firsthop->extend_info->addr);
  320. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  321. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
  322. firsthop->extend_info->port);
  323. /* imprint the circuit with its future n_conn->id */
  324. memcpy(circ->_base.n_conn_id_digest, firsthop->extend_info->identity_digest,
  325. DIGEST_LEN);
  326. n_conn = connection_or_get_by_identity_digest(
  327. firsthop->extend_info->identity_digest);
  328. /* If we don't have an open conn, or the conn we have is obsolete
  329. * (i.e. old or broken) and the other side will let us make a second
  330. * connection without dropping it immediately... */
  331. if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
  332. (n_conn->_base.or_is_obsolete &&
  333. router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
  334. "0.1.1.9-alpha-cvs"))) {
  335. /* not currently connected */
  336. circ->_base.n_addr = firsthop->extend_info->addr;
  337. circ->_base.n_port = firsthop->extend_info->port;
  338. if (!n_conn || n_conn->_base.or_is_obsolete) { /* launch the connection */
  339. n_conn = connection_or_connect(firsthop->extend_info->addr,
  340. firsthop->extend_info->port,
  341. firsthop->extend_info->identity_digest);
  342. if (!n_conn) { /* connect failed, forget the whole thing */
  343. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  344. return -END_CIRC_REASON_CONNECTFAILED;
  345. }
  346. }
  347. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  348. /* return success. The onion/circuit/etc will be taken care of
  349. * automatically (may already have been) whenever n_conn reaches
  350. * OR_CONN_STATE_OPEN.
  351. */
  352. return 0;
  353. } else { /* it's already open. use it. */
  354. circ->_base.n_addr = n_conn->_base.addr;
  355. circ->_base.n_port = n_conn->_base.port;
  356. circ->_base.n_conn = n_conn;
  357. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  358. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  359. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  360. return err_reason;
  361. }
  362. }
  363. return 0;
  364. }
  365. /** Find any circuits that are waiting on <b>or_conn</b> to become
  366. * open and get them to send their create cells forward.
  367. *
  368. * Status is 1 if connect succeeded, or 0 if connect failed.
  369. */
  370. void
  371. circuit_n_conn_done(or_connection_t *or_conn, int status)
  372. {
  373. smartlist_t *pending_circs;
  374. int err_reason = 0;
  375. log_debug(LD_CIRC,"or_conn to %s, status=%d",
  376. or_conn->nickname ? or_conn->nickname : "NULL", status);
  377. pending_circs = smartlist_create();
  378. circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
  379. SMARTLIST_FOREACH(pending_circs, circuit_t *, circ,
  380. {
  381. /* This check is redundant wrt get_all_pending_on_or_conn, but I'm
  382. * leaving them in in case it's possible for the status of a circuit to
  383. * change as we're going down the list. */
  384. if (circ->marked_for_close || circ->n_conn ||
  385. circ->state != CIRCUIT_STATE_OR_WAIT ||
  386. memcmp(or_conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN))
  387. continue;
  388. if (!status) { /* or_conn failed; close circ */
  389. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  390. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  391. continue;
  392. }
  393. log_debug(LD_CIRC, "Found circ, sending create cell.");
  394. /* circuit_deliver_create_cell will set n_circ_id and add us to
  395. * orconn_circuid_circuit_map, so we don't need to call
  396. * set_circid_orconn here. */
  397. circ->n_conn = or_conn;
  398. if (CIRCUIT_IS_ORIGIN(circ)) {
  399. if ((err_reason =
  400. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  401. log_info(LD_CIRC,
  402. "send_next_onion_skin failed; circuit marked for closing.");
  403. circuit_mark_for_close(circ, -err_reason);
  404. continue;
  405. /* XXX could this be bad, eg if next_onion_skin failed because conn
  406. * died? */
  407. }
  408. } else {
  409. /* pull the create cell out of circ->onionskin, and send it */
  410. tor_assert(circ->onionskin);
  411. if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin)<0) {
  412. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  413. continue;
  414. }
  415. tor_free(circ->onionskin);
  416. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  417. }
  418. });
  419. smartlist_free(pending_circs);
  420. }
  421. /** Find a new circid that isn't currently in use on the circ->n_conn
  422. * for the outgoing
  423. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  424. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  425. * to this circuit.
  426. * Return -1 if we failed to find a suitable circid, else return 0.
  427. */
  428. static int
  429. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  430. const char *payload)
  431. {
  432. cell_t cell;
  433. uint16_t id;
  434. tor_assert(circ);
  435. tor_assert(circ->n_conn);
  436. tor_assert(payload);
  437. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  438. id = get_unique_circ_id_by_conn(circ->n_conn);
  439. if (!id) {
  440. log_warn(LD_CIRC,"failed to get unique circID.");
  441. return -1;
  442. }
  443. log_debug(LD_CIRC,"Chosen circID %u.", id);
  444. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  445. memset(&cell, 0, sizeof(cell_t));
  446. cell.command = cell_type;
  447. cell.circ_id = circ->n_circ_id;
  448. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  449. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  450. return 0;
  451. }
  452. /** We've decided to start our reachability testing. If all
  453. * is set, log this to the user. Return 1 if we did, or 0 if
  454. * we chose not to log anything. */
  455. int
  456. inform_testing_reachability(void)
  457. {
  458. char dirbuf[128];
  459. routerinfo_t *me = router_get_my_routerinfo();
  460. if (!me)
  461. return 0;
  462. if (me->dir_port)
  463. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  464. me->address, me->dir_port);
  465. log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  466. "(this may take up to %d minutes -- look for log "
  467. "messages indicating success)",
  468. me->address, me->or_port,
  469. me->dir_port ? dirbuf : "",
  470. me->dir_port ? "are" : "is",
  471. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  472. return 1;
  473. }
  474. /** Return true iff we should send a create_fast cell to build a circuit
  475. * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
  476. * information on the router, so assume true.) */
  477. static INLINE int
  478. should_use_create_fast_for_router(routerinfo_t *router,
  479. origin_circuit_t *circ)
  480. {
  481. or_options_t *options = get_options();
  482. if (!options->FastFirstHopPK) /* create_fast is disabled */
  483. return 0;
  484. if (router && router->platform &&
  485. !tor_version_as_new_as(router->platform, "0.1.0.6-rc")) {
  486. /* known not to work */
  487. return 0;
  488. }
  489. if (server_mode(options) && circ->cpath->extend_info->onion_key) {
  490. /* We're a server, and we know an onion key. We can choose.
  491. * Prefer to blend in. */
  492. return 0;
  493. }
  494. return 1;
  495. }
  496. /** This is the backbone function for building circuits.
  497. *
  498. * If circ's first hop is closed, then we need to build a create
  499. * cell and send it forward.
  500. *
  501. * Otherwise, we need to build a relay extend cell and send it
  502. * forward.
  503. *
  504. * Return -reason if we want to tear down circ, else return 0.
  505. */
  506. int
  507. circuit_send_next_onion_skin(origin_circuit_t *circ)
  508. {
  509. crypt_path_t *hop;
  510. routerinfo_t *router;
  511. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  512. char *onionskin;
  513. size_t payload_len;
  514. tor_assert(circ);
  515. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  516. int fast;
  517. uint8_t cell_type;
  518. log_debug(LD_CIRC,"First skin; sending create cell.");
  519. router = router_get_by_digest(circ->_base.n_conn->identity_digest);
  520. fast = should_use_create_fast_for_router(router, circ);
  521. if (!fast && !circ->cpath->extend_info->onion_key) {
  522. log_warn(LD_CIRC,
  523. "Can't send create_fast, but have no onion key. Failing.");
  524. return - END_CIRC_REASON_INTERNAL;
  525. }
  526. if (!fast) {
  527. /* We are an OR, or we are connecting to an old Tor: we should
  528. * send an old slow create cell.
  529. */
  530. cell_type = CELL_CREATE;
  531. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  532. &(circ->cpath->dh_handshake_state),
  533. payload) < 0) {
  534. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  535. return - END_CIRC_REASON_INTERNAL;
  536. }
  537. } else {
  538. /* We are not an OR, and we're building the first hop of a circuit to a
  539. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  540. * and a DH operation. */
  541. cell_type = CELL_CREATE_FAST;
  542. memset(payload, 0, sizeof(payload));
  543. crypto_rand(circ->cpath->fast_handshake_state,
  544. sizeof(circ->cpath->fast_handshake_state));
  545. memcpy(payload, circ->cpath->fast_handshake_state,
  546. sizeof(circ->cpath->fast_handshake_state));
  547. }
  548. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  549. return - END_CIRC_REASON_RESOURCELIMIT;
  550. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  551. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  552. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  553. fast ? "CREATE_FAST" : "CREATE",
  554. router ? router->nickname : "<unnamed>");
  555. } else {
  556. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  557. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  558. log_debug(LD_CIRC,"starting to send subsequent skin.");
  559. hop = onion_next_hop_in_cpath(circ->cpath);
  560. if (!hop) {
  561. /* done building the circuit. whew. */
  562. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  563. log_info(LD_CIRC,"circuit built!");
  564. circuit_reset_failure_count(0);
  565. if (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
  566. or_options_t *options = get_options();
  567. has_completed_circuit=1;
  568. /* FFFF Log a count of known routers here */
  569. log(LOG_NOTICE, LD_GENERAL,
  570. "Tor has successfully opened a circuit. "
  571. "Looks like client functionality is working.");
  572. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  573. if (server_mode(options) && !check_whether_orport_reachable()) {
  574. inform_testing_reachability();
  575. consider_testing_reachability(1, 1);
  576. }
  577. }
  578. circuit_rep_hist_note_result(circ);
  579. circuit_has_opened(circ); /* do other actions as necessary */
  580. return 0;
  581. }
  582. set_uint32(payload, htonl(hop->extend_info->addr));
  583. set_uint16(payload+4, htons(hop->extend_info->port));
  584. onionskin = payload+2+4;
  585. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  586. hop->extend_info->identity_digest, DIGEST_LEN);
  587. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  588. if (onion_skin_create(hop->extend_info->onion_key,
  589. &(hop->dh_handshake_state), onionskin) < 0) {
  590. log_warn(LD_CIRC,"onion_skin_create failed.");
  591. return - END_CIRC_REASON_INTERNAL;
  592. }
  593. log_debug(LD_CIRC,"Sending extend relay cell.");
  594. /* send it to hop->prev, because it will transfer
  595. * it to a create cell and then send to hop */
  596. if (connection_edge_send_command(NULL, TO_CIRCUIT(circ),
  597. RELAY_COMMAND_EXTEND,
  598. payload, payload_len, hop->prev) < 0)
  599. return 0; /* circuit is closed */
  600. hop->state = CPATH_STATE_AWAITING_KEYS;
  601. }
  602. return 0;
  603. }
  604. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  605. * something has also gone wrong with our network: notify the user,
  606. * and abandon all not-yet-used circuits. */
  607. void
  608. circuit_note_clock_jumped(int seconds_elapsed)
  609. {
  610. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  611. log(severity, LD_GENERAL, "Your clock just jumped %d seconds %s; "
  612. "assuming established circuits no longer work.",
  613. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  614. seconds_elapsed >=0 ? "forward" : "backward");
  615. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  616. seconds_elapsed);
  617. has_completed_circuit=0; /* so it'll log when it works again */
  618. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  619. "CLOCK_JUMPED");
  620. circuit_mark_all_unused_circs();
  621. circuit_expire_all_dirty_circs();
  622. }
  623. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  624. * sure we're connected to the next hop, and pass it the onion skin using
  625. * a create cell. Return -1 if we want to warn and tear down the circuit,
  626. * else return 0.
  627. */
  628. int
  629. circuit_extend(cell_t *cell, circuit_t *circ)
  630. {
  631. or_connection_t *n_conn;
  632. relay_header_t rh;
  633. char *onionskin;
  634. char *id_digest=NULL;
  635. if (circ->n_conn) {
  636. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  637. "n_conn already set. Bug/attack. Closing.");
  638. return -1;
  639. }
  640. if (!server_mode(get_options())) {
  641. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  642. "Got an extend cell, but running as a client. Closing.");
  643. return -1;
  644. }
  645. relay_header_unpack(&rh, cell->payload);
  646. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  647. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  648. "Wrong length %d on extend cell. Closing circuit.",
  649. rh.length);
  650. return -1;
  651. }
  652. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  653. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  654. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  655. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  656. n_conn = connection_or_get_by_identity_digest(id_digest);
  657. /* If we don't have an open conn, or the conn we have is obsolete
  658. * (i.e. old or broken) and the other side will let us make a second
  659. * connection without dropping it immediately... */
  660. if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
  661. (n_conn->_base.or_is_obsolete &&
  662. router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
  663. struct in_addr in;
  664. char tmpbuf[INET_NTOA_BUF_LEN];
  665. in.s_addr = htonl(circ->n_addr);
  666. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  667. log_info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
  668. tmpbuf, circ->n_port);
  669. circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  670. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  671. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  672. /* imprint the circuit with its future n_conn->id */
  673. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  674. if (n_conn && !n_conn->_base.or_is_obsolete) {
  675. circ->n_addr = n_conn->_base.addr;
  676. circ->n_port = n_conn->_base.port;
  677. } else {
  678. /* we should try to open a connection */
  679. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  680. if (!n_conn) {
  681. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  682. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  683. return 0;
  684. }
  685. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  686. }
  687. /* return success. The onion/circuit/etc will be taken care of
  688. * automatically (may already have been) whenever n_conn reaches
  689. * OR_CONN_STATE_OPEN.
  690. */
  691. return 0;
  692. }
  693. /* these may be different if the router connected to us from elsewhere */
  694. circ->n_addr = n_conn->_base.addr;
  695. circ->n_port = n_conn->_base.port;
  696. circ->n_conn = n_conn;
  697. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  698. log_debug(LD_CIRC,"n_conn is %s:%u",
  699. n_conn->_base.address,n_conn->_base.port);
  700. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  701. return -1;
  702. return 0;
  703. }
  704. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  705. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  706. * used as follows:
  707. * - 20 to initialize f_digest
  708. * - 20 to initialize b_digest
  709. * - 16 to key f_crypto
  710. * - 16 to key b_crypto
  711. *
  712. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  713. */
  714. int
  715. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  716. int reverse)
  717. {
  718. crypto_digest_env_t *tmp_digest;
  719. crypto_cipher_env_t *tmp_crypto;
  720. tor_assert(cpath);
  721. tor_assert(key_data);
  722. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  723. cpath->f_digest || cpath->b_digest));
  724. cpath->f_digest = crypto_new_digest_env();
  725. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  726. cpath->b_digest = crypto_new_digest_env();
  727. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  728. if (!(cpath->f_crypto =
  729. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  730. log_warn(LD_BUG,"Bug: forward cipher initialization failed.");
  731. return -1;
  732. }
  733. if (!(cpath->b_crypto =
  734. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  735. log_warn(LD_BUG,"Bug: backward cipher initialization failed.");
  736. return -1;
  737. }
  738. if (reverse) {
  739. tmp_digest = cpath->f_digest;
  740. cpath->f_digest = cpath->b_digest;
  741. cpath->b_digest = tmp_digest;
  742. tmp_crypto = cpath->f_crypto;
  743. cpath->f_crypto = cpath->b_crypto;
  744. cpath->b_crypto = tmp_crypto;
  745. }
  746. return 0;
  747. }
  748. /** A created or extended cell came back to us on the circuit, and it included
  749. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  750. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  751. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  752. *
  753. * Calculate the appropriate keys and digests, make sure KH is
  754. * correct, and initialize this hop of the cpath.
  755. *
  756. * Return - reason if we want to mark circ for close, else return 0.
  757. */
  758. int
  759. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  760. const char *reply)
  761. {
  762. char keys[CPATH_KEY_MATERIAL_LEN];
  763. crypt_path_t *hop;
  764. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  765. hop = circ->cpath;
  766. else {
  767. hop = onion_next_hop_in_cpath(circ->cpath);
  768. if (!hop) { /* got an extended when we're all done? */
  769. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  770. return - END_CIRC_REASON_TORPROTOCOL;
  771. }
  772. }
  773. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  774. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  775. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  776. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  777. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  778. return -END_CIRC_REASON_TORPROTOCOL;
  779. }
  780. /* Remember hash of g^xy */
  781. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  782. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  783. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  784. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  785. log_warn(LD_CIRC,"fast_client_handshake failed.");
  786. return -END_CIRC_REASON_TORPROTOCOL;
  787. }
  788. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  789. } else {
  790. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  791. return -END_CIRC_REASON_TORPROTOCOL;
  792. }
  793. if (hop->dh_handshake_state) {
  794. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  795. hop->dh_handshake_state = NULL;
  796. }
  797. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  798. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  799. return -END_CIRC_REASON_TORPROTOCOL;
  800. }
  801. hop->state = CPATH_STATE_OPEN;
  802. log_info(LD_CIRC,"Finished building %scircuit hop:",
  803. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  804. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  805. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  806. return 0;
  807. }
  808. /** We received a relay truncated cell on circ.
  809. *
  810. * Since we don't ask for truncates currently, getting a truncated
  811. * means that a connection broke or an extend failed. For now,
  812. * just give up: for circ to close, and return 0.
  813. */
  814. int
  815. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  816. {
  817. // crypt_path_t *victim;
  818. // connection_t *stream;
  819. tor_assert(circ);
  820. tor_assert(layer);
  821. /* XXX Since we don't ask for truncates currently, getting a truncated
  822. * means that a connection broke or an extend failed. For now,
  823. * just give up.
  824. */
  825. circuit_mark_for_close(TO_CIRCUIT(circ),
  826. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  827. return 0;
  828. #if 0
  829. while (layer->next != circ->cpath) {
  830. /* we need to clear out layer->next */
  831. victim = layer->next;
  832. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  833. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  834. if (stream->cpath_layer == victim) {
  835. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  836. stream->stream_id);
  837. /* no need to send 'end' relay cells,
  838. * because the other side's already dead
  839. */
  840. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  841. }
  842. }
  843. layer->next = victim->next;
  844. circuit_free_cpath_node(victim);
  845. }
  846. log_info(LD_CIRC, "finished");
  847. return 0;
  848. #endif
  849. }
  850. /** Given a response payload and keys, initialize, then send a created
  851. * cell back.
  852. */
  853. int
  854. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  855. const char *keys)
  856. {
  857. cell_t cell;
  858. crypt_path_t *tmp_cpath;
  859. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  860. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  861. memset(&cell, 0, sizeof(cell_t));
  862. cell.command = cell_type;
  863. cell.circ_id = circ->p_circ_id;
  864. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  865. memcpy(cell.payload, payload,
  866. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  867. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  868. (unsigned int)*(uint32_t*)(keys),
  869. (unsigned int)*(uint32_t*)(keys+20));
  870. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  871. log_warn(LD_BUG,"Circuit initialization failed");
  872. tor_free(tmp_cpath);
  873. return -1;
  874. }
  875. circ->n_digest = tmp_cpath->f_digest;
  876. circ->n_crypto = tmp_cpath->f_crypto;
  877. circ->p_digest = tmp_cpath->b_digest;
  878. circ->p_crypto = tmp_cpath->b_crypto;
  879. tmp_cpath->magic = 0;
  880. tor_free(tmp_cpath);
  881. if (cell_type == CELL_CREATED)
  882. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  883. else
  884. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  885. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  886. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  887. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  888. if (!is_local_IP(circ->p_conn->_base.addr) &&
  889. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  890. /* record that we could process create cells from a non-local conn
  891. * that we didn't initiate; presumably this means that create cells
  892. * can reach us too. */
  893. router_orport_found_reachable();
  894. }
  895. return 0;
  896. }
  897. /** Choose a length for a circuit of purpose <b>purpose</b>.
  898. * Default length is 3 + the number of endpoints that would give something
  899. * away. If the routerlist <b>routers</b> doesn't have enough routers
  900. * to handle the desired path length, return as large a path length as
  901. * is feasible, except if it's less than 2, in which case return -1.
  902. */
  903. static int
  904. new_route_len(uint8_t purpose, extend_info_t *exit,
  905. smartlist_t *routers)
  906. {
  907. int num_acceptable_routers;
  908. int routelen;
  909. tor_assert(routers);
  910. #ifdef TOR_PERF
  911. routelen = 2;
  912. #else
  913. routelen = 3;
  914. if (exit &&
  915. purpose != CIRCUIT_PURPOSE_TESTING &&
  916. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  917. routelen++;
  918. #endif
  919. log_debug(LD_CIRC,"Chosen route length %d (%d routers available).",
  920. routelen, smartlist_len(routers));
  921. num_acceptable_routers = count_acceptable_routers(routers);
  922. if (num_acceptable_routers < 2) {
  923. log_info(LD_CIRC,
  924. "Not enough acceptable routers (%d). Discarding this circuit.",
  925. num_acceptable_routers);
  926. return -1;
  927. }
  928. if (num_acceptable_routers < routelen) {
  929. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  930. routelen, num_acceptable_routers);
  931. routelen = num_acceptable_routers;
  932. }
  933. return routelen;
  934. }
  935. /** Fetch the list of predicted ports, dup it into a smartlist of
  936. * uint16_t's, remove the ones that are already handled by an
  937. * existing circuit, and return it.
  938. */
  939. static smartlist_t *
  940. circuit_get_unhandled_ports(time_t now)
  941. {
  942. smartlist_t *source = rep_hist_get_predicted_ports(now);
  943. smartlist_t *dest = smartlist_create();
  944. uint16_t *tmp;
  945. int i;
  946. for (i = 0; i < smartlist_len(source); ++i) {
  947. tmp = tor_malloc(sizeof(uint16_t));
  948. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  949. smartlist_add(dest, tmp);
  950. }
  951. circuit_remove_handled_ports(dest);
  952. return dest;
  953. }
  954. /** Return 1 if we already have circuits present or on the way for
  955. * all anticipated ports. Return 0 if we should make more.
  956. *
  957. * If we're returning 0, set need_uptime and need_capacity to
  958. * indicate any requirements that the unhandled ports have.
  959. */
  960. int
  961. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  962. int *need_capacity)
  963. {
  964. int i, enough;
  965. uint16_t *port;
  966. smartlist_t *sl = circuit_get_unhandled_ports(now);
  967. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  968. tor_assert(need_uptime);
  969. tor_assert(need_capacity);
  970. enough = (smartlist_len(sl) == 0);
  971. for (i = 0; i < smartlist_len(sl); ++i) {
  972. port = smartlist_get(sl, i);
  973. if (smartlist_string_num_isin(LongLivedServices, *port))
  974. *need_uptime = 1;
  975. tor_free(port);
  976. }
  977. smartlist_free(sl);
  978. return enough;
  979. }
  980. /** Return 1 if <b>router</b> can handle one or more of the ports in
  981. * <b>needed_ports</b>, else return 0.
  982. */
  983. static int
  984. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  985. {
  986. int i;
  987. uint16_t port;
  988. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  989. addr_policy_result_t r;
  990. port = *(uint16_t *)smartlist_get(needed_ports, i);
  991. tor_assert(port);
  992. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  993. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  994. return 1;
  995. }
  996. return 0;
  997. }
  998. /** Return true iff <b>conn</b> needs another general circuit to be
  999. * built. */
  1000. static int
  1001. ap_stream_wants_exit_attention(connection_t *conn)
  1002. {
  1003. if (conn->type == CONN_TYPE_AP &&
  1004. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1005. !conn->marked_for_close &&
  1006. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1007. !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
  1008. MIN_CIRCUITS_HANDLING_STREAM))
  1009. return 1;
  1010. return 0;
  1011. }
  1012. /** Return a pointer to a suitable router to be the exit node for the
  1013. * general-purpose circuit we're about to build.
  1014. *
  1015. * Look through the connection array, and choose a router that maximizes
  1016. * the number of pending streams that can exit from this router.
  1017. *
  1018. * Return NULL if we can't find any suitable routers.
  1019. */
  1020. static routerinfo_t *
  1021. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  1022. int need_capacity)
  1023. {
  1024. int *n_supported;
  1025. int i, j;
  1026. int n_pending_connections = 0;
  1027. connection_t **carray;
  1028. int n_connections;
  1029. int best_support = -1;
  1030. int n_best_support=0;
  1031. smartlist_t *sl, *preferredexits, *excludedexits;
  1032. routerinfo_t *router;
  1033. or_options_t *options = get_options();
  1034. get_connection_array(&carray, &n_connections);
  1035. /* Count how many connections are waiting for a circuit to be built.
  1036. * We use this for log messages now, but in the future we may depend on it.
  1037. */
  1038. for (i = 0; i < n_connections; ++i) {
  1039. if (ap_stream_wants_exit_attention(carray[i]))
  1040. ++n_pending_connections;
  1041. }
  1042. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1043. // n_pending_connections);
  1044. /* Now we count, for each of the routers in the directory, how many
  1045. * of the pending connections could possibly exit from that
  1046. * router (n_supported[i]). (We can't be sure about cases where we
  1047. * don't know the IP address of the pending connection.)
  1048. */
  1049. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  1050. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  1051. router = smartlist_get(dir->routers, i);
  1052. if (router_is_me(router)) {
  1053. n_supported[i] = -1;
  1054. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1055. /* XXX there's probably a reverse predecessor attack here, but
  1056. * it's slow. should we take this out? -RD
  1057. */
  1058. continue;
  1059. }
  1060. if (!router->is_running || router->is_bad_exit) {
  1061. n_supported[i] = -1;
  1062. continue; /* skip routers that are known to be down or bad exits */
  1063. }
  1064. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  1065. n_supported[i] = -1;
  1066. continue; /* skip routers that are not suitable */
  1067. }
  1068. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  1069. /* if it's invalid and we don't want it */
  1070. n_supported[i] = -1;
  1071. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1072. // router->nickname, i);
  1073. continue; /* skip invalid routers */
  1074. }
  1075. if (router_exit_policy_rejects_all(router)) {
  1076. n_supported[i] = -1;
  1077. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1078. // router->nickname, i);
  1079. continue; /* skip routers that reject all */
  1080. }
  1081. n_supported[i] = 0;
  1082. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  1083. if (!ap_stream_wants_exit_attention(carray[j]))
  1084. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1085. if (connection_ap_can_use_exit(TO_EDGE_CONN(carray[j]), router)) {
  1086. ++n_supported[i];
  1087. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1088. // router->nickname, i, n_supported[i]);
  1089. } else {
  1090. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1091. // router->nickname, i);
  1092. }
  1093. } /* End looping over connections. */
  1094. if (n_supported[i] > best_support) {
  1095. /* If this router is better than previous ones, remember its index
  1096. * and goodness, and start counting how many routers are this good. */
  1097. best_support = n_supported[i]; n_best_support=1;
  1098. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1099. // router->nickname);
  1100. } else if (n_supported[i] == best_support) {
  1101. /* If this router is _as good_ as the best one, just increment the
  1102. * count of equally good routers.*/
  1103. ++n_best_support;
  1104. }
  1105. }
  1106. log_info(LD_CIRC,
  1107. "Found %d servers that might support %d/%d pending connections.",
  1108. n_best_support, best_support >= 0 ? best_support : 0,
  1109. n_pending_connections);
  1110. preferredexits = smartlist_create();
  1111. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  1112. excludedexits = smartlist_create();
  1113. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  1114. sl = smartlist_create();
  1115. /* If any routers definitely support any pending connections, choose one
  1116. * at random. */
  1117. if (best_support > 0) {
  1118. for (i = 0; i < smartlist_len(dir->routers); i++)
  1119. if (n_supported[i] == best_support)
  1120. smartlist_add(sl, smartlist_get(dir->routers, i));
  1121. smartlist_subtract(sl,excludedexits);
  1122. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1123. smartlist_intersect(sl,preferredexits);
  1124. router = routerlist_sl_choose_by_bandwidth(sl, 1);
  1125. } else {
  1126. /* Either there are no pending connections, or no routers even seem to
  1127. * possibly support any of them. Choose a router at random that satisfies
  1128. * at least one predicted exit port. */
  1129. int try;
  1130. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1131. if (best_support == -1) {
  1132. if (need_uptime || need_capacity) {
  1133. log_info(LD_CIRC,
  1134. "We couldn't find any live%s%s routers; falling back "
  1135. "to list of all routers.",
  1136. need_capacity?", fast":"",
  1137. need_uptime?", stable":"");
  1138. smartlist_free(preferredexits);
  1139. smartlist_free(excludedexits);
  1140. smartlist_free(sl);
  1141. tor_free(n_supported);
  1142. return choose_good_exit_server_general(dir, 0, 0);
  1143. }
  1144. log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
  1145. "doomed exit at random.");
  1146. }
  1147. for (try = 0; try < 2; try++) {
  1148. /* try once to pick only from routers that satisfy a needed port,
  1149. * then if there are none, pick from any that support exiting. */
  1150. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1151. router = smartlist_get(dir->routers, i);
  1152. if (n_supported[i] != -1 &&
  1153. (try || router_handles_some_port(router, needed_ports))) {
  1154. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1155. // try, router->nickname);
  1156. smartlist_add(sl, router);
  1157. }
  1158. }
  1159. smartlist_subtract(sl,excludedexits);
  1160. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1161. smartlist_intersect(sl,preferredexits);
  1162. /* XXX sometimes the above results in null, when the requested
  1163. * exit node is down. we should pick it anyway. */
  1164. router = routerlist_sl_choose_by_bandwidth(sl, 1);
  1165. if (router)
  1166. break;
  1167. }
  1168. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1169. smartlist_free(needed_ports);
  1170. }
  1171. smartlist_free(preferredexits);
  1172. smartlist_free(excludedexits);
  1173. smartlist_free(sl);
  1174. tor_free(n_supported);
  1175. if (router) {
  1176. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1177. return router;
  1178. }
  1179. if (options->StrictExitNodes) {
  1180. log_warn(LD_CIRC,
  1181. "No specified exit routers seem to be running, and "
  1182. "StrictExitNodes is set: can't choose an exit.");
  1183. }
  1184. return NULL;
  1185. }
  1186. /** Return a pointer to a suitable router to be the exit node for the
  1187. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1188. * if no router is suitable).
  1189. *
  1190. * For general-purpose circuits, pass it off to
  1191. * choose_good_exit_server_general()
  1192. *
  1193. * For client-side rendezvous circuits, choose a random node, weighted
  1194. * toward the preferences in 'options'.
  1195. */
  1196. static routerinfo_t *
  1197. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1198. int need_uptime, int need_capacity, int is_internal)
  1199. {
  1200. or_options_t *options = get_options();
  1201. switch (purpose) {
  1202. case CIRCUIT_PURPOSE_C_GENERAL:
  1203. if (is_internal) /* pick it like a middle hop */
  1204. return router_choose_random_node(NULL, get_options()->ExcludeNodes,
  1205. NULL, need_uptime, need_capacity, 0,
  1206. get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  1207. else
  1208. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  1209. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1210. return router_choose_random_node(
  1211. options->RendNodes, options->RendExcludeNodes,
  1212. NULL, need_uptime, need_capacity, 0,
  1213. options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0, 0);
  1214. }
  1215. log_warn(LD_BUG,"Bug: unhandled purpose %d", purpose);
  1216. tor_fragile_assert();
  1217. return NULL;
  1218. }
  1219. /** Decide a suitable length for circ's cpath, and pick an exit
  1220. * router (or use <b>exit</b> if provided). Store these in the
  1221. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1222. static int
  1223. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1224. {
  1225. cpath_build_state_t *state = circ->build_state;
  1226. routerlist_t *rl = router_get_routerlist();
  1227. if (state->onehop_tunnel) {
  1228. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1229. state->desired_path_len = 1;
  1230. } else {
  1231. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  1232. if (r < 1) /* must be at least 1 */
  1233. return -1;
  1234. state->desired_path_len = r;
  1235. }
  1236. if (exit) { /* the circuit-builder pre-requested one */
  1237. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1238. exit = extend_info_dup(exit);
  1239. } else { /* we have to decide one */
  1240. routerinfo_t *router =
  1241. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  1242. state->need_capacity, state->is_internal);
  1243. if (!router) {
  1244. log_warn(LD_CIRC,"failed to choose an exit server");
  1245. return -1;
  1246. }
  1247. exit = extend_info_from_router(router);
  1248. }
  1249. state->chosen_exit = exit;
  1250. return 0;
  1251. }
  1252. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1253. * hop to the cpath reflecting this. Don't send the next extend cell --
  1254. * the caller will do this if it wants to.
  1255. */
  1256. int
  1257. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info)
  1258. {
  1259. cpath_build_state_t *state;
  1260. tor_assert(info);
  1261. tor_assert(circ);
  1262. state = circ->build_state;
  1263. tor_assert(state);
  1264. if (state->chosen_exit)
  1265. extend_info_free(state->chosen_exit);
  1266. state->chosen_exit = extend_info_dup(info);
  1267. ++circ->build_state->desired_path_len;
  1268. onion_append_hop(&circ->cpath, info);
  1269. return 0;
  1270. }
  1271. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1272. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1273. * send the next extend cell to begin connecting to that hop.
  1274. */
  1275. int
  1276. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info)
  1277. {
  1278. int err_reason = 0;
  1279. circuit_append_new_exit(circ, info);
  1280. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1281. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1282. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1283. info->nickname);
  1284. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1285. return -1;
  1286. }
  1287. return 0;
  1288. }
  1289. /** Return the number of routers in <b>routers</b> that are currently up
  1290. * and available for building circuits through.
  1291. */
  1292. static int
  1293. count_acceptable_routers(smartlist_t *routers)
  1294. {
  1295. int i, n;
  1296. int num=0;
  1297. routerinfo_t *r;
  1298. n = smartlist_len(routers);
  1299. for (i=0;i<n;i++) {
  1300. r = smartlist_get(routers, i);
  1301. // log_debug(LD_CIRC,
  1302. // "Contemplating whether router %d (%s) is a new option.",
  1303. // i, r->nickname);
  1304. if (r->is_running == 0) {
  1305. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1306. goto next_i_loop;
  1307. }
  1308. if (r->is_valid == 0) {
  1309. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1310. goto next_i_loop;
  1311. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1312. * allows this node in some places, then we're getting an inaccurate
  1313. * count. For now, be conservative and don't count it. But later we
  1314. * should try to be smarter. */
  1315. }
  1316. num++;
  1317. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1318. next_i_loop:
  1319. ; /* C requires an explicit statement after the label */
  1320. }
  1321. return num;
  1322. }
  1323. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1324. * This function is used to extend cpath by another hop.
  1325. */
  1326. void
  1327. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1328. {
  1329. if (*head_ptr) {
  1330. new_hop->next = (*head_ptr);
  1331. new_hop->prev = (*head_ptr)->prev;
  1332. (*head_ptr)->prev->next = new_hop;
  1333. (*head_ptr)->prev = new_hop;
  1334. } else {
  1335. *head_ptr = new_hop;
  1336. new_hop->prev = new_hop->next = new_hop;
  1337. }
  1338. }
  1339. /** Pick a random server digest that's running a Tor version that
  1340. * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
  1341. * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
  1342. * probably already connected to them.
  1343. *
  1344. * We only return one, so this doesn't become stupid when the
  1345. * whole network has upgraded. */
  1346. static char *
  1347. compute_preferred_testing_list(const char *answer)
  1348. {
  1349. smartlist_t *choices;
  1350. routerlist_t *rl = router_get_routerlist();
  1351. routerinfo_t *router;
  1352. char *s;
  1353. if (answer) /* they have one in mind -- easy */
  1354. return tor_strdup(answer);
  1355. choices = smartlist_create();
  1356. /* now count up our choices */
  1357. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1358. if (r->is_running && r->is_valid &&
  1359. ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
  1360. !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
  1361. tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
  1362. !is_local_IP(r->addr) &&
  1363. !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
  1364. smartlist_add(choices, r));
  1365. router = smartlist_choose(choices);
  1366. smartlist_free(choices);
  1367. if (!router) {
  1368. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1369. "reachability bug, but didn't find one. Oh well.");
  1370. return NULL;
  1371. }
  1372. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1373. "reachability bug, and chose '%s'. Great.", router->nickname);
  1374. s = tor_malloc(HEX_DIGEST_LEN+2);
  1375. s[0] = '$';
  1376. base16_encode(s+1, HEX_DIGEST_LEN+1,
  1377. router->cache_info.identity_digest, DIGEST_LEN);
  1378. return s;
  1379. }
  1380. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1381. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1382. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1383. * circuit. In particular, make sure we don't pick the exit node or its
  1384. * family, and make sure we don't duplicate any previous nodes or their
  1385. * families. */
  1386. static routerinfo_t *
  1387. choose_good_middle_server(uint8_t purpose,
  1388. cpath_build_state_t *state,
  1389. crypt_path_t *head,
  1390. int cur_len)
  1391. {
  1392. int i;
  1393. routerinfo_t *r, *choice;
  1394. crypt_path_t *cpath;
  1395. smartlist_t *excluded;
  1396. or_options_t *options = get_options();
  1397. char *preferred = NULL;
  1398. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1399. purpose <= _CIRCUIT_PURPOSE_MAX);
  1400. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1401. excluded = smartlist_create();
  1402. if ((r = build_state_get_exit_router(state))) {
  1403. smartlist_add(excluded, r);
  1404. routerlist_add_family(excluded, r);
  1405. }
  1406. if ((r = routerlist_find_my_routerinfo())) {
  1407. smartlist_add(excluded, r);
  1408. routerlist_add_family(excluded, r);
  1409. }
  1410. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1411. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1412. smartlist_add(excluded, r);
  1413. routerlist_add_family(excluded, r);
  1414. }
  1415. }
  1416. if (purpose == CIRCUIT_PURPOSE_TESTING)
  1417. preferred = compute_preferred_testing_list(options->TestVia);
  1418. choice = router_choose_random_node(preferred,
  1419. options->ExcludeNodes, excluded,
  1420. state->need_uptime, state->need_capacity, 0,
  1421. options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  1422. if (preferred)
  1423. tor_free(preferred);
  1424. smartlist_free(excluded);
  1425. return choice;
  1426. }
  1427. /** Pick a good entry server for the circuit to be built according to
  1428. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1429. * router (if we're an OR), and respect firewall settings; if we're
  1430. * using entry_guards, return one.
  1431. *
  1432. * If <b>state</b> is NULL, we're choosing routers to serve as entry
  1433. * nodes, not for any particular circuit.
  1434. */
  1435. static routerinfo_t *
  1436. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1437. {
  1438. routerinfo_t *r, *choice;
  1439. smartlist_t *excluded;
  1440. or_options_t *options = get_options();
  1441. (void)purpose; /* not used yet. */
  1442. if (state && options->UseEntryGuards) {
  1443. return choose_random_entry(state);
  1444. }
  1445. excluded = smartlist_create();
  1446. if (state && (r = build_state_get_exit_router(state))) {
  1447. smartlist_add(excluded, r);
  1448. routerlist_add_family(excluded, r);
  1449. }
  1450. if ((r = routerlist_find_my_routerinfo())) {
  1451. smartlist_add(excluded, r);
  1452. routerlist_add_family(excluded, r);
  1453. }
  1454. if (firewall_is_fascist_or()) {
  1455. /* exclude all ORs that listen on the wrong port */
  1456. routerlist_t *rl = router_get_routerlist();
  1457. int i;
  1458. for (i=0; i < smartlist_len(rl->routers); i++) {
  1459. r = smartlist_get(rl->routers, i);
  1460. if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
  1461. smartlist_add(excluded, r);
  1462. }
  1463. }
  1464. /* and exclude current entry guards, if applicable */
  1465. if (options->UseEntryGuards && entry_guards) {
  1466. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1467. {
  1468. if ((r = router_get_by_digest(entry->identity)))
  1469. smartlist_add(excluded, r);
  1470. });
  1471. }
  1472. choice = router_choose_random_node(
  1473. NULL, options->ExcludeNodes,
  1474. excluded, state ? state->need_uptime : 0,
  1475. state ? state->need_capacity : 0,
  1476. state ? 0 : 1,
  1477. options->_AllowInvalid & ALLOW_INVALID_ENTRY, 0, 0);
  1478. smartlist_free(excluded);
  1479. return choice;
  1480. }
  1481. /** Return the first non-open hop in cpath, or return NULL if all
  1482. * hops are open. */
  1483. static crypt_path_t *
  1484. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1485. {
  1486. crypt_path_t *hop = cpath;
  1487. do {
  1488. if (hop->state != CPATH_STATE_OPEN)
  1489. return hop;
  1490. hop = hop->next;
  1491. } while (hop != cpath);
  1492. return NULL;
  1493. }
  1494. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1495. * based on <b>state</b>. Append the hop info to head_ptr.
  1496. */
  1497. static int
  1498. onion_extend_cpath(origin_circuit_t *circ)
  1499. {
  1500. uint8_t purpose = circ->_base.purpose;
  1501. cpath_build_state_t *state = circ->build_state;
  1502. int cur_len = circuit_get_cpath_len(circ);
  1503. extend_info_t *info = NULL;
  1504. if (cur_len >= state->desired_path_len) {
  1505. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1506. state->desired_path_len);
  1507. return 1;
  1508. }
  1509. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1510. state->desired_path_len);
  1511. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1512. info = extend_info_dup(state->chosen_exit);
  1513. } else if (cur_len == 0) { /* picking first node */
  1514. routerinfo_t *r = choose_good_entry_server(purpose, state);
  1515. if (r)
  1516. info = extend_info_from_router(r);
  1517. } else {
  1518. routerinfo_t *r =
  1519. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1520. if (r)
  1521. info = extend_info_from_router(r);
  1522. }
  1523. if (!info) {
  1524. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1525. "this circuit.", cur_len);
  1526. return -1;
  1527. }
  1528. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1529. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1530. onion_append_hop(&circ->cpath, info);
  1531. extend_info_free(info);
  1532. return 0;
  1533. }
  1534. /** Create a new hop, annotate it with information about its
  1535. * corresponding router <b>choice</b>, and append it to the
  1536. * end of the cpath <b>head_ptr</b>. */
  1537. static int
  1538. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1539. {
  1540. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1541. /* link hop into the cpath, at the end. */
  1542. onion_append_to_cpath(head_ptr, hop);
  1543. hop->magic = CRYPT_PATH_MAGIC;
  1544. hop->state = CPATH_STATE_CLOSED;
  1545. hop->extend_info = extend_info_dup(choice);
  1546. hop->package_window = CIRCWINDOW_START;
  1547. hop->deliver_window = CIRCWINDOW_START;
  1548. return 0;
  1549. }
  1550. /** Allocate and return a new extend_info_t that can be used to build a
  1551. * circuit to or through the router <b>r</b>. */
  1552. extend_info_t *
  1553. extend_info_from_router(routerinfo_t *r)
  1554. {
  1555. extend_info_t *info;
  1556. tor_assert(r);
  1557. info = tor_malloc_zero(sizeof(extend_info_t));
  1558. strlcpy(info->nickname, r->nickname, sizeof(info->nickname));
  1559. memcpy(info->identity_digest, r->cache_info.identity_digest, DIGEST_LEN);
  1560. info->onion_key = crypto_pk_dup_key(r->onion_pkey);
  1561. info->addr = r->addr;
  1562. info->port = r->or_port;
  1563. return info;
  1564. }
  1565. /** Allocate and return a new extend_info_t that can be used to build a
  1566. * circuit to or through the router <b>r</b>. */
  1567. extend_info_t *
  1568. extend_info_from_routerstatus(routerstatus_t *s)
  1569. {
  1570. extend_info_t *info;
  1571. tor_assert(s);
  1572. info = tor_malloc_zero(sizeof(extend_info_t));
  1573. strlcpy(info->nickname, s->nickname, sizeof(info->nickname));
  1574. memcpy(info->identity_digest, s->identity_digest, DIGEST_LEN);
  1575. info->onion_key = NULL; /* routerstatus doesn't know this */
  1576. info->addr = s->addr;
  1577. info->port = s->or_port;
  1578. return info;
  1579. }
  1580. /** Release storage held by an extend_info_t struct. */
  1581. void
  1582. extend_info_free(extend_info_t *info)
  1583. {
  1584. tor_assert(info);
  1585. if (info->onion_key)
  1586. crypto_free_pk_env(info->onion_key);
  1587. tor_free(info);
  1588. }
  1589. /** Allocate and return a new extend_info_t with the same contents as
  1590. * <b>info</b>. */
  1591. extend_info_t *
  1592. extend_info_dup(extend_info_t *info)
  1593. {
  1594. extend_info_t *newinfo;
  1595. tor_assert(info);
  1596. newinfo = tor_malloc(sizeof(extend_info_t));
  1597. memcpy(newinfo, info, sizeof(extend_info_t));
  1598. if (info->onion_key)
  1599. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1600. else
  1601. newinfo->onion_key = NULL;
  1602. return newinfo;
  1603. }
  1604. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1605. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1606. * the chosen exit, return NULL.
  1607. */
  1608. routerinfo_t *
  1609. build_state_get_exit_router(cpath_build_state_t *state)
  1610. {
  1611. if (!state || !state->chosen_exit)
  1612. return NULL;
  1613. return router_get_by_digest(state->chosen_exit->identity_digest);
  1614. }
  1615. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1616. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1617. * chosen exit, return NULL.
  1618. */
  1619. const char *
  1620. build_state_get_exit_nickname(cpath_build_state_t *state)
  1621. {
  1622. if (!state || !state->chosen_exit)
  1623. return NULL;
  1624. return state->chosen_exit->nickname;
  1625. }
  1626. /** Check whether the entry guard <b>e</b> is usable, given the directory
  1627. * authorities' opinion about the rouer (stored in <b>ri</b>) and the user's
  1628. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  1629. * accordingly. Return true iff the entry guard's status changes. */
  1630. static int
  1631. entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
  1632. time_t now, or_options_t *options)
  1633. {
  1634. const char *reason = NULL;
  1635. char buf[HEX_DIGEST_LEN+1];
  1636. int changed = 0;
  1637. tor_assert(options);
  1638. /* Do we want to mark this guard as bad? */
  1639. if (!ri)
  1640. reason = "unlisted";
  1641. else if (!ri->is_running)
  1642. reason = "down";
  1643. else if (!ri->is_possible_guard &&
  1644. !router_nickname_is_in_list(ri, options->EntryNodes))
  1645. reason = "not recommended as a guard";
  1646. else if (router_nickname_is_in_list(ri, options->ExcludeNodes))
  1647. reason = "excluded";
  1648. if (reason && ! e->bad_since) {
  1649. /* Router is newly bad. */
  1650. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1651. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  1652. e->nickname, buf, reason);
  1653. e->bad_since = now;
  1654. control_event_guard(e->nickname, e->identity, "BAD");
  1655. changed = 1;
  1656. } else if (!reason && e->bad_since) {
  1657. /* There's nothing wrong with the router any more. */
  1658. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1659. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  1660. "marking as ok.", e->nickname, buf);
  1661. e->bad_since = 0;
  1662. control_event_guard(e->nickname, e->identity, "GOOD");
  1663. changed = 1;
  1664. }
  1665. return changed;
  1666. }
  1667. /** Return true iff enough time has passed since we last tried connect to the
  1668. * unreachable guard <b>e</b> that we're willing to try again. */
  1669. static int
  1670. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  1671. {
  1672. long diff;
  1673. if (e->last_attempted < e->unreachable_since)
  1674. return 1;
  1675. diff = now - e->unreachable_since;
  1676. if (diff < 6*60*60)
  1677. return now > (e->last_attempted + 60*60);
  1678. else if (diff < 3*24*60*60)
  1679. return now > (e->last_attempted + 4*60*60);
  1680. else if (diff < 7*24*60*60)
  1681. return now > (e->last_attempted + 18*60*60);
  1682. else
  1683. return now > (e->last_attempted + 36*60*60);
  1684. }
  1685. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  1686. * working well enough that we are willing to use it as an entry
  1687. * right now. (Else return NULL.) In particular, it must be
  1688. * - Listed as either up or never yet contacted;
  1689. * - Present in the routerlist;
  1690. * - Listed as 'stable' or 'fast' by the current dirserver concensus,
  1691. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
  1692. * (This check is currently redundant with the Guard flag, but in
  1693. * the future that might change. Best to leave it in for now.)
  1694. * - Allowed by our current ReachableAddresses config option; and
  1695. * - Currently thought to be reachable by us (unless assume_reachable
  1696. * is true).
  1697. */
  1698. static INLINE routerinfo_t *
  1699. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  1700. int assume_reachable)
  1701. {
  1702. routerinfo_t *r;
  1703. if (e->bad_since)
  1704. return NULL;
  1705. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  1706. if ((!assume_reachable && !e->can_retry) &&
  1707. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
  1708. return NULL;
  1709. r = router_get_by_digest(e->identity);
  1710. if (!r)
  1711. return NULL;
  1712. if (router_is_unreliable(r, need_uptime, need_capacity, 0))
  1713. return NULL;
  1714. if (firewall_is_fascist_or() &&
  1715. !fascist_firewall_allows_address_or(r->addr,r->or_port))
  1716. return NULL;
  1717. return r;
  1718. }
  1719. /** Return the number of entry guards that we think are usable. */
  1720. static int
  1721. num_live_entry_guards(void)
  1722. {
  1723. int n = 0;
  1724. if (! entry_guards)
  1725. return 0;
  1726. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1727. {
  1728. if (entry_is_live(entry, 0, 1, 0))
  1729. ++n;
  1730. });
  1731. return n;
  1732. }
  1733. /** Return 1 if <b>digest</b> matches the identity of any node
  1734. * in the entry_guards list. Else return 0. */
  1735. static INLINE int
  1736. is_an_entry_guard(const char *digest)
  1737. {
  1738. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1739. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  1740. return 1;
  1741. );
  1742. return 0;
  1743. }
  1744. /** Dump a description of our list of entry guards to the log at level
  1745. * <b>severity</b>. */
  1746. static void
  1747. log_entry_guards(int severity)
  1748. {
  1749. smartlist_t *elements = smartlist_create();
  1750. char buf[1024];
  1751. char *s;
  1752. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1753. {
  1754. tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
  1755. e->nickname,
  1756. e->bad_since ? "down " : "up ",
  1757. e->made_contact ? "made-contact" : "never-contacted");
  1758. smartlist_add(elements, tor_strdup(buf));
  1759. });
  1760. s = smartlist_join_strings(elements, ",", 0, NULL);
  1761. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1762. smartlist_free(elements);
  1763. log_fn(severity,LD_CIRC,"%s",s);
  1764. tor_free(s);
  1765. }
  1766. /** Called when one or more guards that we would previously have used for some
  1767. * purpose are no longer in use because a higher-priority guard has become
  1768. * useable again. */
  1769. static void
  1770. control_event_guard_deferred(void)
  1771. {
  1772. /* XXXX We don't actually have a good way to figure out _how many_ entries
  1773. * are live for some purpose. We need an entry_is_even_slightly_live()
  1774. * function for this to work right. NumEntryGuards isn't reliable: if we
  1775. * need guards with weird properties, we can have more than that number
  1776. * live.
  1777. **/
  1778. #if 0
  1779. int n = 0;
  1780. or_options_t *options = get_options();
  1781. if (!entry_guards)
  1782. return;
  1783. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1784. {
  1785. if (entry_is_live(entry, 0, 1, 0)) {
  1786. if (n++ == options->NumEntryGuards) {
  1787. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  1788. return;
  1789. }
  1790. }
  1791. });
  1792. #endif
  1793. }
  1794. /** Add a new (preferably stable and fast) router to our
  1795. * entry_guards list. Return a pointer to the router if we succeed,
  1796. * or NULL if we can't find any more suitable entries.
  1797. *
  1798. * If <b>chosen</b> is defined, use that one, and if it's not
  1799. * already in our entry_guards list, put it at the *beginning*.
  1800. * Else, put the one we pick at the end of the list. */
  1801. static routerinfo_t *
  1802. add_an_entry_guard(routerinfo_t *chosen)
  1803. {
  1804. routerinfo_t *router;
  1805. entry_guard_t *entry;
  1806. if (chosen) {
  1807. router = chosen;
  1808. if (is_an_entry_guard(router->cache_info.identity_digest))
  1809. return NULL;
  1810. } else {
  1811. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  1812. if (!router)
  1813. return NULL;
  1814. }
  1815. entry = tor_malloc_zero(sizeof(entry_guard_t));
  1816. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  1817. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  1818. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  1819. if (chosen) /* prepend */
  1820. smartlist_insert(entry_guards, 0, entry);
  1821. else /* append */
  1822. smartlist_add(entry_guards, entry);
  1823. control_event_guard(entry->nickname, entry->identity, "NEW");
  1824. control_event_guard_deferred();
  1825. log_entry_guards(LOG_INFO);
  1826. return router;
  1827. }
  1828. /** If the use of entry guards is configured, choose more entry guards
  1829. * until we have enough in the list. */
  1830. static void
  1831. pick_entry_guards(void)
  1832. {
  1833. or_options_t *options = get_options();
  1834. int changed = 0;
  1835. tor_assert(entry_guards);
  1836. while (num_live_entry_guards() < options->NumEntryGuards) {
  1837. if (!add_an_entry_guard(NULL))
  1838. break;
  1839. changed = 1;
  1840. }
  1841. if (changed)
  1842. entry_guards_changed();
  1843. }
  1844. /** Release all storage held by the list of entry guards. */
  1845. void
  1846. entry_guards_free_all(void)
  1847. {
  1848. if (entry_guards) {
  1849. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  1850. smartlist_free(entry_guards);
  1851. entry_guards = NULL;
  1852. }
  1853. }
  1854. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1855. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1856. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1857. /** Remove all entry guards that have been down or unlisted for so
  1858. * long that we don't think they'll come up again. Return 1 if we
  1859. * removed any, or 0 if we did nothing. */
  1860. static int
  1861. remove_dead_entries(void)
  1862. {
  1863. char dbuf[HEX_DIGEST_LEN+1];
  1864. char tbuf[ISO_TIME_LEN+1];
  1865. time_t now = time(NULL);
  1866. int i;
  1867. int changed = 0;
  1868. for (i = 0; i < smartlist_len(entry_guards); ) {
  1869. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1870. if (entry->bad_since &&
  1871. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  1872. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  1873. format_local_iso_time(tbuf, entry->bad_since);
  1874. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  1875. "since %s local time; removing.",
  1876. entry->nickname, dbuf, tbuf);
  1877. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  1878. tor_free(entry);
  1879. smartlist_del_keeporder(entry_guards, i);
  1880. log_entry_guards(LOG_INFO);
  1881. changed = 1;
  1882. } else
  1883. ++i;
  1884. }
  1885. return changed ? 1 : 0;
  1886. }
  1887. /** A new directory or router-status has arrived; update the down/listed
  1888. * status of the entry guards.
  1889. *
  1890. * An entry is 'down' if the directory lists it as nonrunning.
  1891. * An entry is 'unlisted' if the directory doesn't include it.
  1892. */
  1893. void
  1894. entry_guards_compute_status(void)
  1895. {
  1896. /* Don't call this on startup; only on a fresh download. Otherwise we'll
  1897. * think that things are unlisted. */
  1898. time_t now;
  1899. int changed = 0;
  1900. int severity = LOG_INFO;
  1901. or_options_t *options;
  1902. if (! entry_guards)
  1903. return;
  1904. options = get_options();
  1905. now = time(NULL);
  1906. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1907. {
  1908. routerinfo_t *r = router_get_by_digest(entry->identity);
  1909. if (entry_guard_set_status(entry, r, now, options))
  1910. changed = 1;
  1911. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s and %s.",
  1912. entry->nickname,
  1913. entry->unreachable_since ? "unreachable" : "reachable",
  1914. entry->bad_since ? "unusable" : "usable",
  1915. entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
  1916. });
  1917. if (remove_dead_entries())
  1918. changed = 1;
  1919. if (changed) {
  1920. log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
  1921. num_live_entry_guards(), smartlist_len(entry_guards));
  1922. log_entry_guards(LOG_INFO);
  1923. entry_guards_changed();
  1924. }
  1925. }
  1926. /** Called when a connection to an OR with the identity digest <b>digest</b>
  1927. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  1928. * If the OR is an entry, change that entry's up/down status.
  1929. * Return 0 normally, or -1 if we want to tear down the new connection.
  1930. */
  1931. int
  1932. entry_guard_register_connect_status(const char *digest, int succeeded,
  1933. time_t now)
  1934. {
  1935. int changed = 0;
  1936. int refuse_conn = 0;
  1937. int first_contact = 0;
  1938. entry_guard_t *entry = NULL;
  1939. int idx = -1;
  1940. char buf[HEX_DIGEST_LEN+1];
  1941. if (! entry_guards)
  1942. return 0;
  1943. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1944. {
  1945. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  1946. entry = e;
  1947. idx = e_sl_idx;
  1948. break;
  1949. }
  1950. });
  1951. if (!entry)
  1952. return 0;
  1953. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  1954. if (succeeded) {
  1955. if (entry->unreachable_since) {
  1956. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  1957. entry->nickname, buf);
  1958. entry->can_retry = 0;
  1959. entry->unreachable_since = 0;
  1960. entry->last_attempted = now;
  1961. control_event_guard(entry->nickname, entry->identity, "UP");
  1962. changed = 1;
  1963. }
  1964. if (!entry->made_contact) {
  1965. entry->made_contact = 1;
  1966. first_contact = changed = 1;
  1967. }
  1968. } else { /* ! succeeded */
  1969. if (!entry->made_contact) {
  1970. /* We've never connected to this one. */
  1971. log_info(LD_CIRC,
  1972. "Connection to never-contacted entry guard '%s' (%s) failed. "
  1973. "Removing from the list. %d/%d entry guards usable/new.",
  1974. entry->nickname, buf,
  1975. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  1976. tor_free(entry);
  1977. smartlist_del_keeporder(entry_guards, idx);
  1978. log_entry_guards(LOG_INFO);
  1979. changed = 1;
  1980. } else if (!entry->unreachable_since) {
  1981. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  1982. "Marking as unreachable.", entry->nickname, buf);
  1983. entry->unreachable_since = entry->last_attempted = now;
  1984. control_event_guard(entry->nickname, entry->identity, "DOWN");
  1985. changed = 1;
  1986. } else {
  1987. char tbuf[ISO_TIME_LEN+1];
  1988. format_iso_time(tbuf, entry->unreachable_since);
  1989. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  1990. "'%s' (%s). It has been unreachable since %s.",
  1991. entry->nickname, buf, tbuf);
  1992. entry->last_attempted = now;
  1993. }
  1994. if (entry)
  1995. entry->can_retry = 0; /* We gave it an early chance; no good. */
  1996. }
  1997. if (first_contact) {
  1998. /* We've just added a new long-term entry guard. Perhaps the network just
  1999. * came back? We should give our earlier entries another try too,
  2000. * and close this connection so we don't use it before we've given
  2001. * the others a shot. */
  2002. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2003. if (e == entry)
  2004. break;
  2005. if (e->made_contact) {
  2006. routerinfo_t *r = entry_is_live(e, 0, 1, 1);
  2007. if (r && e->unreachable_since) {
  2008. refuse_conn = 1;
  2009. e->can_retry = 1;
  2010. }
  2011. }
  2012. });
  2013. if (refuse_conn) {
  2014. log_info(LD_CIRC,
  2015. "Connected to new entry guard '%s' (%s). Marking earlier "
  2016. "entry guards up. %d/%d entry guards usable/new.",
  2017. entry->nickname, buf,
  2018. num_live_entry_guards(), smartlist_len(entry_guards));
  2019. log_entry_guards(LOG_INFO);
  2020. changed = 1;
  2021. }
  2022. }
  2023. if (changed)
  2024. entry_guards_changed();
  2025. return refuse_conn ? -1 : 0;
  2026. }
  2027. /** When we try to choose an entry guard, should we parse and add
  2028. * config's EntryNodes first? */
  2029. static int should_add_entry_nodes = 0;
  2030. /** Called when the value of EntryNodes changes in our configuration. */
  2031. void
  2032. entry_nodes_should_be_added(void)
  2033. {
  2034. log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
  2035. should_add_entry_nodes = 1;
  2036. }
  2037. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  2038. * of guard nodes, at the front. */
  2039. static void
  2040. entry_guards_prepend_from_config(void)
  2041. {
  2042. or_options_t *options = get_options();
  2043. smartlist_t *entry_routers = smartlist_create();
  2044. smartlist_t *old_entry_guards_on_list = smartlist_create();
  2045. smartlist_t *old_entry_guards_not_on_list = smartlist_create();
  2046. smartlist_t *entry_fps = smartlist_create();
  2047. tor_assert(entry_guards);
  2048. should_add_entry_nodes = 0;
  2049. if (!options->EntryNodes) {
  2050. /* It's possible that a controller set EntryNodes, thus making
  2051. * should_add_entry_nodes set, then cleared it again, all before the
  2052. * call to choose_random_entry() that triggered us. If so, just return.
  2053. */
  2054. return;
  2055. }
  2056. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
  2057. options->EntryNodes);
  2058. /* Split entry guards into those on the list and those not. */
  2059. add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
  2060. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  2061. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  2062. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2063. if (smartlist_digest_isin(entry_fps, e->identity))
  2064. smartlist_add(old_entry_guards_on_list, e);
  2065. else
  2066. smartlist_add(old_entry_guards_not_on_list, e);
  2067. });
  2068. /* Remove all currently configured entry guards from entry_routers. */
  2069. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2070. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  2071. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  2072. }
  2073. });
  2074. /* Now build the new entry_guards list. */
  2075. smartlist_clear(entry_guards);
  2076. /* First, the previously configured guards that are in EntryNodes. */
  2077. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  2078. /* Next, the rest of EntryNodes */
  2079. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2080. add_an_entry_guard(ri);
  2081. });
  2082. /* Finally, the remaining EntryNodes, unless we're strict */
  2083. if (options->StrictEntryNodes) {
  2084. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2085. tor_free(e));
  2086. } else {
  2087. smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
  2088. }
  2089. smartlist_free(entry_routers);
  2090. smartlist_free(entry_fps);
  2091. smartlist_free(old_entry_guards_on_list);
  2092. smartlist_free(old_entry_guards_not_on_list);
  2093. entry_guards_changed();
  2094. }
  2095. /** Pick a live (up and listed) entry guard from entry_guards, and
  2096. * make sure not to pick this circuit's exit. */
  2097. static routerinfo_t *
  2098. choose_random_entry(cpath_build_state_t *state)
  2099. {
  2100. or_options_t *options = get_options();
  2101. smartlist_t *live_entry_guards = smartlist_create();
  2102. routerinfo_t *chosen_exit = build_state_get_exit_router(state);
  2103. routerinfo_t *r = NULL;
  2104. int need_uptime = state->need_uptime;
  2105. int need_capacity = state->need_capacity;
  2106. if (!entry_guards)
  2107. entry_guards = smartlist_create();
  2108. if (should_add_entry_nodes)
  2109. entry_guards_prepend_from_config();
  2110. if (!options->StrictEntryNodes &&
  2111. (! entry_guards ||
  2112. smartlist_len(entry_guards) < options->NumEntryGuards))
  2113. pick_entry_guards();
  2114. retry:
  2115. smartlist_clear(live_entry_guards);
  2116. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2117. {
  2118. r = entry_is_live(entry, need_uptime, need_capacity, 0);
  2119. if (r && r != chosen_exit) {
  2120. smartlist_add(live_entry_guards, r);
  2121. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  2122. break; /* we have enough */
  2123. }
  2124. });
  2125. /* Try to have at least 2 choices available. This way we don't
  2126. * get stuck with a single live-but-crummy entry and just keep
  2127. * using him.
  2128. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  2129. if (smartlist_len(live_entry_guards) < 2) {
  2130. if (!options->StrictEntryNodes) {
  2131. /* still no? try adding a new entry then */
  2132. /* XXX if guard doesn't imply fast and stable, then we need
  2133. * to tell add_an_entry_guard below what we want, or it might
  2134. * be a long time til we get it. -RD */
  2135. r = add_an_entry_guard(NULL);
  2136. if (r) {
  2137. smartlist_add(live_entry_guards, r);
  2138. entry_guards_changed();
  2139. }
  2140. }
  2141. if (!r && need_uptime) {
  2142. need_uptime = 0; /* try without that requirement */
  2143. goto retry;
  2144. }
  2145. if (!r && need_capacity) {
  2146. /* still no? last attempt, try without requiring capacity */
  2147. need_capacity = 0;
  2148. goto retry;
  2149. }
  2150. /* live_entry_guards will be empty below. Oh well, we tried. */
  2151. }
  2152. r = smartlist_choose(live_entry_guards);
  2153. smartlist_free(live_entry_guards);
  2154. return r;
  2155. }
  2156. /** Parse <b>state</b> and learn about the entry guards it describes.
  2157. * If <b>set</b> is true, and there are no errors, replace the global
  2158. * entry_list with what we find.
  2159. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2160. * describing the error, and return -1.
  2161. */
  2162. int
  2163. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2164. {
  2165. entry_guard_t *node = NULL;
  2166. smartlist_t *new_entry_guards = smartlist_create();
  2167. config_line_t *line;
  2168. *msg = NULL;
  2169. for (line = state->EntryGuards; line; line = line->next) {
  2170. if (!strcasecmp(line->key, "EntryGuard")) {
  2171. smartlist_t *args = smartlist_create();
  2172. node = tor_malloc_zero(sizeof(entry_guard_t));
  2173. /* all entry guards on disk have been contacted */
  2174. node->made_contact = 1;
  2175. smartlist_add(new_entry_guards, node);
  2176. smartlist_split_string(args, line->value, " ",
  2177. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2178. if (smartlist_len(args)<2) {
  2179. *msg = tor_strdup("Unable to parse entry nodes: "
  2180. "Too few arguments to EntryGuard");
  2181. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  2182. *msg = tor_strdup("Unable to parse entry nodes: "
  2183. "Bad nickname for EntryGuard");
  2184. } else {
  2185. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  2186. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  2187. strlen(smartlist_get(args,1)))<0) {
  2188. *msg = tor_strdup("Unable to parse entry nodes: "
  2189. "Bad hex digest for EntryGuard");
  2190. }
  2191. }
  2192. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  2193. smartlist_free(args);
  2194. if (*msg)
  2195. break;
  2196. } else {
  2197. time_t when;
  2198. time_t last_try = 0;
  2199. if (!node) {
  2200. *msg = tor_strdup("Unable to parse entry nodes: "
  2201. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  2202. break;
  2203. }
  2204. if (parse_iso_time(line->value, &when)<0) {
  2205. *msg = tor_strdup("Unable to parse entry nodes: "
  2206. "Bad time in EntryGuardDownSince/UnlistedSince");
  2207. break;
  2208. }
  2209. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  2210. /* ignore failure */
  2211. parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  2212. }
  2213. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  2214. node->unreachable_since = when;
  2215. node->last_attempted = last_try;
  2216. } else {
  2217. node->bad_since = when;
  2218. }
  2219. }
  2220. }
  2221. if (*msg || !set) {
  2222. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e, tor_free(e));
  2223. smartlist_free(new_entry_guards);
  2224. } else { /* !*err && set */
  2225. if (entry_guards) {
  2226. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  2227. smartlist_free(entry_guards);
  2228. }
  2229. entry_guards = new_entry_guards;
  2230. entry_guards_dirty = 0;
  2231. }
  2232. return *msg ? -1 : 0;
  2233. }
  2234. /** Our list of entry guards has changed, or some element of one
  2235. * of our entry guards has changed. Write the changes to disk within
  2236. * the next few minutes.
  2237. */
  2238. static void
  2239. entry_guards_changed(void)
  2240. {
  2241. time_t when;
  2242. entry_guards_dirty = 1;
  2243. /* or_state_save() will call entry_guards_update_state(). */
  2244. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  2245. or_state_mark_dirty(get_or_state(), when);
  2246. }
  2247. /** If the entry guard info has not changed, do nothing and return.
  2248. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2249. * a new one out of the global entry_guards list, and then mark
  2250. * <b>state</b> dirty so it will get saved to disk.
  2251. */
  2252. void
  2253. entry_guards_update_state(or_state_t *state)
  2254. {
  2255. config_line_t **next, *line;
  2256. if (! entry_guards_dirty)
  2257. return;
  2258. config_free_lines(state->EntryGuards);
  2259. next = &state->EntryGuards;
  2260. *next = NULL;
  2261. if (!entry_guards)
  2262. entry_guards = smartlist_create();
  2263. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2264. {
  2265. char dbuf[HEX_DIGEST_LEN+1];
  2266. if (!e->made_contact)
  2267. continue; /* don't write this one to disk */
  2268. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2269. line->key = tor_strdup("EntryGuard");
  2270. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  2271. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2272. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  2273. "%s %s", e->nickname, dbuf);
  2274. next = &(line->next);
  2275. if (e->unreachable_since) {
  2276. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2277. line->key = tor_strdup("EntryGuardDownSince");
  2278. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  2279. format_iso_time(line->value, e->unreachable_since);
  2280. if (e->last_attempted) {
  2281. line->value[ISO_TIME_LEN] = ' ';
  2282. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  2283. }
  2284. next = &(line->next);
  2285. }
  2286. if (e->bad_since) {
  2287. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2288. line->key = tor_strdup("EntryGuardUnlistedSince");
  2289. line->value = tor_malloc(ISO_TIME_LEN+1);
  2290. format_iso_time(line->value, e->bad_since);
  2291. next = &(line->next);
  2292. }
  2293. });
  2294. if (!get_options()->AvoidDiskWrites)
  2295. or_state_mark_dirty(get_or_state(), 0);
  2296. entry_guards_dirty = 0;
  2297. }
  2298. /** If <b>question</b> is the string "entry-guards", then dump
  2299. * to *<b>answer</b> a newly allocated string describing all of
  2300. * the nodes in the global entry_guards list. See control-spec.txt
  2301. * for details.
  2302. * For backward compatibility, we also handle the string "helper-nodes".
  2303. * */
  2304. int
  2305. getinfo_helper_entry_guards(control_connection_t *conn,
  2306. const char *question, char **answer)
  2307. {
  2308. int use_long_names = conn->use_long_names;
  2309. if (!strcmp(question,"entry-guards") ||
  2310. !strcmp(question,"helper-nodes")) {
  2311. smartlist_t *sl = smartlist_create();
  2312. char tbuf[ISO_TIME_LEN+1];
  2313. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2314. if (!entry_guards)
  2315. entry_guards = smartlist_create();
  2316. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2317. {
  2318. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  2319. char *c = tor_malloc(len);
  2320. const char *status = NULL;
  2321. time_t when = 0;
  2322. if (!e->made_contact) {
  2323. status = "never-connected";
  2324. } else if (e->bad_since) {
  2325. when = e->bad_since;
  2326. status = "unusable";
  2327. } else {
  2328. status = "up";
  2329. }
  2330. if (use_long_names) {
  2331. routerinfo_t *ri = router_get_by_digest(e->identity);
  2332. if (ri) {
  2333. router_get_verbose_nickname(nbuf, ri);
  2334. } else {
  2335. nbuf[0] = '$';
  2336. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2337. /* e->nickname field is not very reliable if we don't know about
  2338. * this router any longer; don't include it. */
  2339. }
  2340. } else {
  2341. base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
  2342. }
  2343. if (when) {
  2344. format_iso_time(tbuf, when);
  2345. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  2346. } else {
  2347. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  2348. }
  2349. smartlist_add(sl, c);
  2350. });
  2351. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2352. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2353. smartlist_free(sl);
  2354. }
  2355. return 0;
  2356. }