circuitbuild.c 77 KB

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