circuitbuild.c 76 KB

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