circuitbuild.c 64 KB

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