circuitbuild.c 79 KB

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