circuitbuild.c 78 KB

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