circuitbuild.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  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 vulnerability.
  70. */
  71. log_fn(LOG_WARN,"No unused circ IDs. Failing.");
  72. return 0;
  73. }
  74. test_circ_id |= high_bit;
  75. } while (circuit_get_by_circid_orconn(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, circuit_t *circ)
  137. {
  138. char *s = circuit_list_path(circ,1);
  139. log_fn(severity,"%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,"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, 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. log_fn(LOG_INFO,"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. log_fn(LOG_DEBUG,"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. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  326. return -1;
  327. }
  328. }
  329. log_fn(LOG_DEBUG,"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. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  339. if (circuit_send_next_onion_skin(circ) < 0) {
  340. log_fn(LOG_INFO,"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. log_fn(LOG_DEBUG,"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. log_fn(LOG_INFO,"or_conn failed. Closing circ.");
  367. circuit_mark_for_close(circ);
  368. continue;
  369. }
  370. log_fn(LOG_DEBUG,"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. log_fn(LOG_INFO,"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. log_fn(LOG_WARN,"failed to get unique circID.");
  409. return -1;
  410. }
  411. log_fn(LOG_DEBUG,"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. extern int has_completed_circuit;
  421. /** This is the backbone function for building circuits.
  422. *
  423. * If circ's first hop is closed, then we need to build a create
  424. * cell and send it forward.
  425. *
  426. * Otherwise, we need to build a relay extend cell and send it
  427. * forward.
  428. *
  429. * Return -1 if we want to tear down circ, else return 0.
  430. */
  431. int
  432. circuit_send_next_onion_skin(circuit_t *circ)
  433. {
  434. crypt_path_t *hop;
  435. routerinfo_t *router;
  436. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  437. char *onionskin;
  438. size_t payload_len;
  439. tor_assert(circ);
  440. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  441. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  442. uint8_t cell_type;
  443. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  444. router = router_get_by_digest(circ->n_conn->identity_digest);
  445. if (1 || /* Disable this '1' once we believe CREATE_FAST works. XXXX */
  446. (get_options()->ORPort || !router || !router->platform ||
  447. !tor_version_as_new_as(router->platform, "0.1.0.6-rc"))) {
  448. /* We are an OR, or we are connecting to an old Tor: we should
  449. * send an old slow create cell.
  450. */
  451. cell_type = CELL_CREATE;
  452. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  453. &(circ->cpath->dh_handshake_state),
  454. payload) < 0) {
  455. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  456. return -1;
  457. }
  458. } else {
  459. /* We are not an OR, and we building the first hop of a circuit to
  460. * a new OR: we can be speedy. */
  461. cell_type = CELL_CREATE_FAST;
  462. memset(payload, 0, sizeof(payload));
  463. crypto_rand(circ->cpath->fast_handshake_state,
  464. sizeof(circ->cpath->fast_handshake_state));
  465. memcpy(payload, circ->cpath->fast_handshake_state,
  466. sizeof(circ->cpath->fast_handshake_state));
  467. }
  468. if (circuit_deliver_create_cell(circ, cell_type, payload) < 0)
  469. return -1;
  470. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  471. circ->state = CIRCUIT_STATE_BUILDING;
  472. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  473. } else {
  474. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  475. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  476. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  477. hop = onion_next_hop_in_cpath(circ->cpath);
  478. if (!hop) {
  479. /* done building the circuit. whew. */
  480. circ->state = CIRCUIT_STATE_OPEN;
  481. log_fn(LOG_INFO,"circuit built!");
  482. circuit_reset_failure_count(0);
  483. if (!has_completed_circuit) {
  484. or_options_t *options = get_options();
  485. has_completed_circuit=1;
  486. log(LOG_NOTICE,"Tor has successfully opened a circuit. Looks like it's working.");
  487. /* XXX009 Log a count of known routers here */
  488. if (server_mode(options) && !check_whether_orport_reachable())
  489. log(LOG_NOTICE,"Now checking whether ORPort %s%s reachable... (this may take several minutes)",
  490. options->DirPort ? "and DirPort " : "",
  491. options->DirPort ? "are" : "is");
  492. }
  493. circuit_rep_hist_note_result(circ);
  494. circuit_has_opened(circ); /* do other actions as necessary */
  495. return 0;
  496. }
  497. *(uint32_t*)payload = htonl(hop->extend_info->addr);
  498. *(uint16_t*)(payload+4) = htons(hop->extend_info->port);
  499. onionskin = payload+2+4;
  500. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->extend_info->identity_digest, DIGEST_LEN);
  501. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  502. if (onion_skin_create(hop->extend_info->onion_key,
  503. &(hop->dh_handshake_state), onionskin) < 0) {
  504. log_fn(LOG_WARN,"onion_skin_create failed.");
  505. return -1;
  506. }
  507. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  508. /* send it to hop->prev, because it will transfer
  509. * it to a create cell and then send to hop */
  510. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  511. payload, payload_len, hop->prev) < 0)
  512. return 0; /* circuit is closed */
  513. hop->state = CPATH_STATE_AWAITING_KEYS;
  514. }
  515. return 0;
  516. }
  517. /** Our clock just jumped forward by <b>seconds_elapsed</b>. Assume
  518. * something has also gone wrong with our network: notify the user,
  519. * and abandon all not-yet-used circuits. */
  520. void
  521. circuit_note_clock_jumped(int seconds_elapsed)
  522. {
  523. log(LOG_NOTICE,"Your clock just jumped %d seconds forward; assuming established circuits no longer work.", seconds_elapsed);
  524. has_completed_circuit=0; /* so it'll log when it works again */
  525. circuit_mark_all_unused_circs();
  526. }
  527. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  528. * sure we're connected to the next hop, and pass it the onion skin in
  529. * a create cell.
  530. */
  531. int
  532. circuit_extend(cell_t *cell, circuit_t *circ)
  533. {
  534. connection_t *n_conn;
  535. relay_header_t rh;
  536. char *onionskin;
  537. char *id_digest=NULL;
  538. if (circ->n_conn) {
  539. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  540. return -1;
  541. }
  542. relay_header_unpack(&rh, cell->payload);
  543. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  544. log_fn(LOG_WARN, "Wrong length %d on extend cell. Closing circuit.", rh.length);
  545. return -1;
  546. }
  547. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  548. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  549. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  550. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  551. n_conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  552. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN) {
  553. /* Note that this will close circuits where the onion has the same
  554. * router twice in a row in the path. I think that's ok.
  555. */
  556. struct in_addr in;
  557. char tmpbuf[INET_NTOA_BUF_LEN];
  558. in.s_addr = htonl(circ->n_addr);
  559. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  560. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Connecting.",
  561. tmpbuf, circ->n_port);
  562. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  563. circ->state = CIRCUIT_STATE_OR_WAIT;
  564. /* imprint the circuit with its future n_conn->id */
  565. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  566. if (n_conn) {
  567. circ->n_addr = n_conn->addr;
  568. circ->n_port = n_conn->port;
  569. } else {
  570. /* we should try to open a connection */
  571. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  572. if (!n_conn) {
  573. log_fn(LOG_INFO,"Launching n_conn failed. Closing.");
  574. return -1;
  575. }
  576. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  577. }
  578. /* return success. The onion/circuit/etc will be taken care of automatically
  579. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  580. */
  581. return 0;
  582. }
  583. /* these may be different if the router connected to us from elsewhere */
  584. circ->n_addr = n_conn->addr;
  585. circ->n_port = n_conn->port;
  586. circ->n_conn = n_conn;
  587. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  588. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  589. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  590. return -1;
  591. return 0;
  592. }
  593. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  594. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  595. * used as follows:
  596. * - 20 to initialize f_digest
  597. * - 20 to initialize b_digest
  598. * - 16 to key f_crypto
  599. * - 16 to key b_crypto
  600. *
  601. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  602. */
  603. int
  604. circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  605. {
  606. crypto_digest_env_t *tmp_digest;
  607. crypto_cipher_env_t *tmp_crypto;
  608. tor_assert(cpath);
  609. tor_assert(key_data);
  610. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  611. cpath->f_digest || cpath->b_digest));
  612. // log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  613. // (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  614. cpath->f_digest = crypto_new_digest_env();
  615. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  616. cpath->b_digest = crypto_new_digest_env();
  617. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  618. // log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  619. // (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  620. if (!(cpath->f_crypto =
  621. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  622. log(LOG_WARN,"Bug: forward cipher initialization failed.");
  623. return -1;
  624. }
  625. if (!(cpath->b_crypto =
  626. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  627. log(LOG_WARN,"Bug: backward cipher initialization failed.");
  628. return -1;
  629. }
  630. if (reverse) {
  631. tmp_digest = cpath->f_digest;
  632. cpath->f_digest = cpath->b_digest;
  633. cpath->b_digest = tmp_digest;
  634. tmp_crypto = cpath->f_crypto;
  635. cpath->f_crypto = cpath->b_crypto;
  636. cpath->b_crypto = tmp_crypto;
  637. }
  638. return 0;
  639. }
  640. /** A created or extended cell came back to us on the circuit,
  641. * and it included <b>reply</b> (the second DH key, plus KH).
  642. * DOCDOC reply_type.
  643. *
  644. * Calculate the appropriate keys and digests, make sure KH is
  645. * correct, and initialize this hop of the cpath.
  646. *
  647. * Return -1 if we want to mark circ for close, else return 0.
  648. */
  649. int
  650. circuit_finish_handshake(circuit_t *circ, uint8_t reply_type, char *reply)
  651. {
  652. char keys[CPATH_KEY_MATERIAL_LEN];
  653. crypt_path_t *hop;
  654. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  655. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  656. hop = circ->cpath;
  657. else {
  658. hop = onion_next_hop_in_cpath(circ->cpath);
  659. if (!hop) { /* got an extended when we're all done? */
  660. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  661. return -1;
  662. }
  663. }
  664. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  665. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  666. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  667. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  668. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  669. return -1;
  670. }
  671. /* Remember hash of g^xy */
  672. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  673. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  674. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  675. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  676. log_fn(LOG_WARN,"fast_client_handshake failed.");
  677. return -1;
  678. }
  679. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  680. } else {
  681. log_fn(LOG_WARN,"CREATED cell type did not match CREATE cell type.");
  682. return -1;
  683. }
  684. if (hop->dh_handshake_state) {
  685. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  686. hop->dh_handshake_state = NULL;
  687. }
  688. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  689. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  690. return -1;
  691. }
  692. hop->state = CPATH_STATE_OPEN;
  693. log_fn(LOG_INFO,"Finished building circuit hop:");
  694. circuit_log_path(LOG_INFO,circ);
  695. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED);
  696. return 0;
  697. }
  698. /** We received a relay truncated cell on circ.
  699. *
  700. * Since we don't ask for truncates currently, getting a truncated
  701. * means that a connection broke or an extend failed. For now,
  702. * just give up: for circ to close, and return 0.
  703. */
  704. int
  705. circuit_truncated(circuit_t *circ, crypt_path_t *layer)
  706. {
  707. // crypt_path_t *victim;
  708. // connection_t *stream;
  709. tor_assert(circ);
  710. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  711. tor_assert(layer);
  712. /* XXX Since we don't ask for truncates currently, getting a truncated
  713. * means that a connection broke or an extend failed. For now,
  714. * just give up.
  715. */
  716. circuit_mark_for_close(circ);
  717. return 0;
  718. #if 0
  719. while (layer->next != circ->cpath) {
  720. /* we need to clear out layer->next */
  721. victim = layer->next;
  722. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  723. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  724. if (stream->cpath_layer == victim) {
  725. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  726. /* no need to send 'end' relay cells,
  727. * because the other side's already dead
  728. */
  729. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  730. }
  731. }
  732. layer->next = victim->next;
  733. circuit_free_cpath_node(victim);
  734. }
  735. log_fn(LOG_INFO, "finished");
  736. return 0;
  737. #endif
  738. }
  739. /** Given a response payload and keys, initialize, then send a created
  740. * cell back.
  741. */
  742. int
  743. onionskin_answer(circuit_t *circ, uint8_t cell_type, char *payload, char *keys)
  744. {
  745. cell_t cell;
  746. crypt_path_t *tmp_cpath;
  747. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  748. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  749. memset(&cell, 0, sizeof(cell_t));
  750. cell.command = cell_type;
  751. cell.circ_id = circ->p_circ_id;
  752. circ->state = CIRCUIT_STATE_OPEN;
  753. memcpy(cell.payload, payload,
  754. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  755. log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
  756. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  757. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  758. log_fn(LOG_WARN,"Circuit initialization failed");
  759. tor_free(tmp_cpath);
  760. return -1;
  761. }
  762. circ->n_digest = tmp_cpath->f_digest;
  763. circ->n_crypto = tmp_cpath->f_crypto;
  764. circ->p_digest = tmp_cpath->b_digest;
  765. circ->p_crypto = tmp_cpath->b_crypto;
  766. tmp_cpath->magic = 0;
  767. tor_free(tmp_cpath);
  768. if (cell_type == CELL_CREATED)
  769. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  770. else
  771. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  772. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  773. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  774. if (!is_local_IP(circ->p_conn->addr) &&
  775. tor_tls_is_server(circ->p_conn->tls)) {
  776. /* record that we could process create cells from a non-local conn
  777. * that we didn't initiate; presumably this means that create cells
  778. * can reach us too. */
  779. router_orport_found_reachable();
  780. }
  781. return 0;
  782. }
  783. /** Choose a length for a circuit of purpose <b>purpose</b>.
  784. * Default length is 3 + the number of endpoints that would give something
  785. * away. If the routerlist <b>routers</b> doesn't have enough routers
  786. * to handle the desired path length, return as large a path length as
  787. * is feasible, except if it's less than 2, in which case return -1.
  788. */
  789. static int
  790. new_route_len(double cw, uint8_t purpose, smartlist_t *routers)
  791. {
  792. int num_acceptable_routers;
  793. int routelen;
  794. tor_assert(cw >= 0.);
  795. tor_assert(cw < 1.);
  796. tor_assert(routers);
  797. #ifdef TOR_PERF
  798. routelen = 2;
  799. #else
  800. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  801. routelen = 3;
  802. else if (purpose == CIRCUIT_PURPOSE_TESTING)
  803. routelen = 3;
  804. else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  805. routelen = 4;
  806. else if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  807. routelen = 3;
  808. else if (purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  809. routelen = 3;
  810. else if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
  811. routelen = 4;
  812. else {
  813. log_fn(LOG_WARN,"Bug: unhandled purpose %d", purpose);
  814. tor_fragile_assert();
  815. return -1;
  816. }
  817. #endif
  818. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen,
  819. smartlist_len(routers));
  820. num_acceptable_routers = count_acceptable_routers(routers);
  821. if (num_acceptable_routers < 2) {
  822. log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
  823. num_acceptable_routers);
  824. return -1;
  825. }
  826. if (num_acceptable_routers < routelen) {
  827. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
  828. routelen, num_acceptable_routers);
  829. routelen = num_acceptable_routers;
  830. }
  831. return routelen;
  832. }
  833. /** Fetch the list of predicted ports, dup it into a smartlist of
  834. * uint16_t's, remove the ones that are already handled by an
  835. * existing circuit, and return it.
  836. */
  837. static smartlist_t *
  838. circuit_get_unhandled_ports(time_t now)
  839. {
  840. smartlist_t *source = rep_hist_get_predicted_ports(now);
  841. smartlist_t *dest = smartlist_create();
  842. uint16_t *tmp;
  843. int i;
  844. for (i = 0; i < smartlist_len(source); ++i) {
  845. tmp = tor_malloc(sizeof(uint16_t));
  846. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  847. smartlist_add(dest, tmp);
  848. }
  849. circuit_remove_handled_ports(dest);
  850. return dest;
  851. }
  852. /** Return 1 if we already have circuits present or on the way for
  853. * all anticipated ports. Return 0 if we should make more.
  854. *
  855. * If we're returning 0, set need_uptime and need_capacity to
  856. * indicate any requirements that the unhandled ports have.
  857. */
  858. int
  859. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  860. int *need_capacity)
  861. {
  862. int i, enough;
  863. uint16_t *port;
  864. smartlist_t *sl = circuit_get_unhandled_ports(now);
  865. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  866. enough = (smartlist_len(sl) == 0);
  867. for (i = 0; i < smartlist_len(sl); ++i) {
  868. port = smartlist_get(sl, i);
  869. if (smartlist_string_num_isin(LongLivedServices, *port))
  870. *need_uptime = 1;
  871. tor_free(port);
  872. }
  873. smartlist_free(sl);
  874. return enough;
  875. }
  876. /** Return 1 if <b>router</b> can handle one or more of the ports in
  877. * <b>needed_ports</b>, else return 0.
  878. */
  879. static int
  880. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  881. {
  882. int i;
  883. uint16_t port;
  884. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  885. addr_policy_result_t r;
  886. port = *(uint16_t *)smartlist_get(needed_ports, i);
  887. tor_assert(port);
  888. r = router_compare_addr_to_addr_policy(0, port, router->exit_policy);
  889. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  890. return 1;
  891. }
  892. return 0;
  893. }
  894. /** How many circuits do we want simultaneously in-progress to handle
  895. * a given stream?
  896. */
  897. #define MIN_CIRCUITS_HANDLING_STREAM 2
  898. static int
  899. ap_stream_wants_exit_attention(connection_t *conn)
  900. {
  901. if (conn->type == CONN_TYPE_AP &&
  902. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  903. !conn->marked_for_close &&
  904. !connection_edge_is_rendezvous_stream(conn) &&
  905. !circuit_stream_is_being_handled(conn, 0, MIN_CIRCUITS_HANDLING_STREAM))
  906. return 1;
  907. return 0;
  908. }
  909. /** Return a pointer to a suitable router to be the exit node for the
  910. * general-purpose circuit we're about to build.
  911. *
  912. * Look through the connection array, and choose a router that maximizes
  913. * the number of pending streams that can exit from this router.
  914. *
  915. * Return NULL if we can't find any suitable routers.
  916. */
  917. static routerinfo_t *
  918. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  919. int need_capacity)
  920. {
  921. int *n_supported;
  922. int i, j;
  923. int n_pending_connections = 0;
  924. connection_t **carray;
  925. int n_connections;
  926. int best_support = -1;
  927. int n_best_support=0;
  928. smartlist_t *sl, *preferredexits, *preferredentries, *excludedexits;
  929. routerinfo_t *router;
  930. or_options_t *options = get_options();
  931. preferredentries = smartlist_create();
  932. add_nickname_list_to_smartlist(preferredentries,options->EntryNodes,1);
  933. get_connection_array(&carray, &n_connections);
  934. /* Count how many connections are waiting for a circuit to be built.
  935. * We use this for log messages now, but in the future we may depend on it.
  936. */
  937. for (i = 0; i < n_connections; ++i) {
  938. if (ap_stream_wants_exit_attention(carray[i]))
  939. ++n_pending_connections;
  940. }
  941. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  942. // n_pending_connections);
  943. /* Now we count, for each of the routers in the directory, how many
  944. * of the pending connections could possibly exit from that
  945. * router (n_supported[i]). (We can't be sure about cases where we
  946. * don't know the IP address of the pending connection.)
  947. */
  948. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  949. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  950. router = smartlist_get(dir->routers, i);
  951. if (router_is_me(router)) {
  952. n_supported[i] = -1;
  953. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  954. /* XXX there's probably a reverse predecessor attack here, but
  955. * it's slow. should we take this out? -RD
  956. */
  957. continue;
  958. }
  959. if (!router->is_running) {
  960. n_supported[i] = -1;
  961. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  962. // router->nickname, i);
  963. continue; /* skip routers that are known to be down */
  964. }
  965. if (router_is_unreliable(router, need_uptime, need_capacity)) {
  966. n_supported[i] = -1;
  967. continue; /* skip routers that are not suitable */
  968. }
  969. if (!router->is_verified &&
  970. (!(options->_AllowUnverified & ALLOW_UNVERIFIED_EXIT) ||
  971. router_is_unreliable(router, 1, 1))) {
  972. /* if it's unverified, and either we don't want it or it's unsuitable */
  973. n_supported[i] = -1;
  974. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  975. // router->nickname, i);
  976. continue; /* skip unverified routers */
  977. }
  978. if (router_exit_policy_rejects_all(router)) {
  979. n_supported[i] = -1;
  980. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  981. // router->nickname, i);
  982. continue; /* skip routers that reject all */
  983. }
  984. if (smartlist_len(preferredentries)==1 &&
  985. router == (routerinfo_t*)smartlist_get(preferredentries, 0)) {
  986. n_supported[i] = -1;
  987. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it's our only preferred entry node.", router->nickname, i);
  988. continue;
  989. }
  990. n_supported[i] = 0;
  991. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  992. if (!ap_stream_wants_exit_attention(carray[j]))
  993. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  994. if (connection_ap_can_use_exit(carray[j], router)) {
  995. ++n_supported[i];
  996. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  997. // router->nickname, i, n_supported[i]);
  998. } else {
  999. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1000. // router->nickname, i);
  1001. }
  1002. } /* End looping over connections. */
  1003. if (n_supported[i] > best_support) {
  1004. /* If this router is better than previous ones, remember its index
  1005. * and goodness, and start counting how many routers are this good. */
  1006. best_support = n_supported[i]; n_best_support=1;
  1007. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1008. // router->nickname);
  1009. } else if (n_supported[i] == best_support) {
  1010. /* If this router is _as good_ as the best one, just increment the
  1011. * count of equally good routers.*/
  1012. ++n_best_support;
  1013. }
  1014. }
  1015. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  1016. n_best_support, best_support, n_pending_connections);
  1017. preferredexits = smartlist_create();
  1018. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  1019. excludedexits = smartlist_create();
  1020. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  1021. sl = smartlist_create();
  1022. /* If any routers definitely support any pending connections, choose one
  1023. * at random. */
  1024. if (best_support > 0) {
  1025. for (i = 0; i < smartlist_len(dir->routers); i++)
  1026. if (n_supported[i] == best_support)
  1027. smartlist_add(sl, smartlist_get(dir->routers, i));
  1028. smartlist_subtract(sl,excludedexits);
  1029. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1030. smartlist_intersect(sl,preferredexits);
  1031. router = routerlist_sl_choose_by_bandwidth(sl);
  1032. } else {
  1033. /* Either there are no pending connections, or no routers even seem to
  1034. * possibly support any of them. Choose a router at random that satisfies
  1035. * at least one predicted exit port. */
  1036. int try;
  1037. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1038. if (best_support == -1) {
  1039. log(LOG_NOTICE, "All routers are down or middleman -- choosing a doomed exit at random.");
  1040. }
  1041. for (try = 0; try < 2; try++) {
  1042. /* try once to pick only from routers that satisfy a needed port,
  1043. * then if there are none, pick from any that support exiting. */
  1044. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1045. router = smartlist_get(dir->routers, i);
  1046. if (n_supported[i] != -1 &&
  1047. (try || router_handles_some_port(router, needed_ports))) {
  1048. log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.", try, router->nickname);
  1049. smartlist_add(sl, router);
  1050. }
  1051. }
  1052. smartlist_subtract(sl,excludedexits);
  1053. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1054. smartlist_intersect(sl,preferredexits);
  1055. router = routerlist_sl_choose_by_bandwidth(sl);
  1056. if (router)
  1057. break;
  1058. }
  1059. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1060. smartlist_free(needed_ports);
  1061. }
  1062. smartlist_free(preferredexits);
  1063. smartlist_free(preferredentries);
  1064. smartlist_free(excludedexits);
  1065. smartlist_free(sl);
  1066. tor_free(n_supported);
  1067. if (router) {
  1068. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  1069. return router;
  1070. }
  1071. if (options->StrictExitNodes)
  1072. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  1073. return NULL;
  1074. }
  1075. /** Return a pointer to a suitable router to be the exit node for the
  1076. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1077. * if no router is suitable).
  1078. *
  1079. * For general-purpose circuits, pass it off to
  1080. * choose_good_exit_server_general()
  1081. *
  1082. * For client-side rendezvous circuits, choose a random node, weighted
  1083. * toward the preferences in 'options'.
  1084. */
  1085. static routerinfo_t *
  1086. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1087. int need_uptime, int need_capacity)
  1088. {
  1089. routerinfo_t *r;
  1090. or_options_t *options = get_options();
  1091. switch (purpose) {
  1092. case CIRCUIT_PURPOSE_C_GENERAL:
  1093. return choose_good_exit_server_general(dir, need_uptime, need_capacity);
  1094. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1095. r = router_choose_random_node(options->RendNodes, options->RendExcludeNodes,
  1096. NULL, need_uptime, need_capacity,
  1097. options->_AllowUnverified & ALLOW_UNVERIFIED_RENDEZVOUS, 0);
  1098. return r;
  1099. }
  1100. log_fn(LOG_WARN,"Bug: unhandled purpose %d", purpose);
  1101. tor_fragile_assert();
  1102. return NULL;
  1103. }
  1104. /** Decide a suitable length for circ's cpath, and pick an exit
  1105. * router (or use <b>exit</b> if provided). Store these in the
  1106. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1107. static int
  1108. onion_pick_cpath_exit(circuit_t *circ, extend_info_t *exit)
  1109. {
  1110. cpath_build_state_t *state = circ->build_state;
  1111. routerlist_t *rl;
  1112. int r;
  1113. router_get_routerlist(&rl);
  1114. if (!rl) {
  1115. log_fn(LOG_WARN,"router_get_routerlist returned empty list; closing circ.");
  1116. return -1;
  1117. }
  1118. r = new_route_len(get_options()->PathlenCoinWeight, circ->purpose, rl->routers);
  1119. if (r < 1) /* must be at least 1 */
  1120. return -1;
  1121. state->desired_path_len = r;
  1122. if (exit) { /* the circuit-builder pre-requested one */
  1123. log_fn(LOG_INFO,"Using requested exit node '%s'", exit->nickname);
  1124. exit = extend_info_dup(exit);
  1125. } else { /* we have to decide one */
  1126. routerinfo_t *router =
  1127. choose_good_exit_server(circ->purpose, rl,
  1128. state->need_uptime, state->need_capacity);
  1129. if (!router) {
  1130. log_fn(LOG_WARN,"failed to choose an exit server");
  1131. return -1;
  1132. }
  1133. exit = extend_info_from_router(router);
  1134. }
  1135. state->chosen_exit = exit;
  1136. return 0;
  1137. }
  1138. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1139. * hop to the cpath reflecting this. Don't send the next extend cell --
  1140. * the caller will do this if it wants to.
  1141. */
  1142. int
  1143. circuit_append_new_exit(circuit_t *circ, extend_info_t *info)
  1144. {
  1145. cpath_build_state_t *state;
  1146. tor_assert(info);
  1147. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  1148. state = circ->build_state;
  1149. tor_assert(state);
  1150. if (state->chosen_exit)
  1151. extend_info_free(state->chosen_exit);
  1152. state->chosen_exit = extend_info_dup(info);
  1153. ++circ->build_state->desired_path_len;
  1154. onion_append_hop(&circ->cpath, info);
  1155. return 0;
  1156. }
  1157. /** DOCDOC */
  1158. int
  1159. circuit_extend_to_new_exit(circuit_t *circ, extend_info_t *info)
  1160. {
  1161. circuit_append_new_exit(circ, info);
  1162. circ->state = CIRCUIT_STATE_BUILDING;
  1163. if (circuit_send_next_onion_skin(circ)<0) {
  1164. log_fn(LOG_WARN, "Couldn't extend circuit to new point '%s'.",
  1165. info->nickname);
  1166. circuit_mark_for_close(circ);
  1167. return -1;
  1168. }
  1169. return 0;
  1170. }
  1171. /** Return the number of routers in <b>routers</b> that are currently up
  1172. * and available for building circuits through.
  1173. */
  1174. static int
  1175. count_acceptable_routers(smartlist_t *routers)
  1176. {
  1177. int i, n;
  1178. int num=0;
  1179. routerinfo_t *r;
  1180. n = smartlist_len(routers);
  1181. for (i=0;i<n;i++) {
  1182. r = smartlist_get(routers, i);
  1183. // log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  1184. // i, r->nickname);
  1185. if (r->is_running == 0) {
  1186. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  1187. goto next_i_loop;
  1188. }
  1189. if (r->is_verified == 0) {
  1190. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  1191. /* XXXX009 But unverified routers *are* sometimes acceptable. */
  1192. goto next_i_loop;
  1193. }
  1194. num++;
  1195. // log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  1196. next_i_loop:
  1197. ; /* C requires an explicit statement after the label */
  1198. }
  1199. return num;
  1200. }
  1201. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1202. *
  1203. * This function is used to extend cpath by another hop.
  1204. */
  1205. void
  1206. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1207. {
  1208. if (*head_ptr) {
  1209. new_hop->next = (*head_ptr);
  1210. new_hop->prev = (*head_ptr)->prev;
  1211. (*head_ptr)->prev->next = new_hop;
  1212. (*head_ptr)->prev = new_hop;
  1213. } else {
  1214. *head_ptr = new_hop;
  1215. new_hop->prev = new_hop->next = new_hop;
  1216. }
  1217. }
  1218. /** DOCDOC */
  1219. static routerinfo_t *
  1220. choose_good_middle_server(uint8_t purpose,
  1221. cpath_build_state_t *state,
  1222. crypt_path_t *head,
  1223. int cur_len)
  1224. {
  1225. int i;
  1226. routerinfo_t *r, *choice;
  1227. crypt_path_t *cpath;
  1228. smartlist_t *excluded;
  1229. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  1230. excluded = smartlist_create();
  1231. if ((r = build_state_get_exit_router(state))) {
  1232. smartlist_add(excluded, r);
  1233. routerlist_add_family(excluded, r);
  1234. }
  1235. if ((r = routerlist_find_my_routerinfo())) {
  1236. smartlist_add(excluded, r);
  1237. routerlist_add_family(excluded, r);
  1238. }
  1239. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1240. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1241. smartlist_add(excluded, r);
  1242. routerlist_add_family(excluded, r);
  1243. }
  1244. }
  1245. choice = router_choose_random_node(NULL, get_options()->ExcludeNodes, excluded,
  1246. state->need_uptime, state->need_capacity,
  1247. get_options()->_AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  1248. smartlist_free(excluded);
  1249. return choice;
  1250. }
  1251. /** Pick a good entry server for the circuit to be built according to
  1252. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this router
  1253. * (if we're an OR), and respect firewall settings; if we're using helper nodes,
  1254. * return one.
  1255. *
  1256. * If <b>state</b> is NULL, we're choosing entries to serve as helper nodes,
  1257. * not for any particular circuit.
  1258. */
  1259. static routerinfo_t *
  1260. choose_good_entry_server(cpath_build_state_t *state)
  1261. {
  1262. routerinfo_t *r, *choice;
  1263. smartlist_t *excluded = smartlist_create();
  1264. or_options_t *options = get_options();
  1265. if (state && options->UseHelperNodes) {
  1266. return choose_random_helper();
  1267. }
  1268. if (state && (r = build_state_get_exit_router(state))) {
  1269. smartlist_add(excluded, r);
  1270. routerlist_add_family(excluded, r);
  1271. }
  1272. if ((r = routerlist_find_my_routerinfo())) {
  1273. smartlist_add(excluded, r);
  1274. routerlist_add_family(excluded, r);
  1275. }
  1276. if (options->FascistFirewall) {
  1277. /* exclude all ORs that listen on the wrong port */
  1278. routerlist_t *rl;
  1279. int i;
  1280. router_get_routerlist(&rl);
  1281. if (!rl)
  1282. return NULL;
  1283. for (i=0; i < smartlist_len(rl->routers); i++) {
  1284. r = smartlist_get(rl->routers, i);
  1285. if (!smartlist_string_num_isin(options->FirewallPorts, r->or_port))
  1286. smartlist_add(excluded, r);
  1287. }
  1288. }
  1289. choice = router_choose_random_node(options->EntryNodes, options->ExcludeNodes,
  1290. excluded, state ? state->need_uptime : 1,
  1291. state ? state->need_capacity : 0,
  1292. options->_AllowUnverified & ALLOW_UNVERIFIED_ENTRY,
  1293. options->StrictEntryNodes);
  1294. smartlist_free(excluded);
  1295. return choice;
  1296. }
  1297. /** Return the first non-open hop in cpath, or return NULL if all
  1298. * hops are open. */
  1299. static crypt_path_t *
  1300. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1301. {
  1302. crypt_path_t *hop = cpath;
  1303. do {
  1304. if (hop->state != CPATH_STATE_OPEN)
  1305. return hop;
  1306. hop = hop->next;
  1307. } while (hop != cpath);
  1308. return NULL;
  1309. }
  1310. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1311. * based on <b>state</b>. Append the hop info to head_ptr.
  1312. */
  1313. static int
  1314. onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  1315. cpath_build_state_t *state)
  1316. {
  1317. int cur_len;
  1318. crypt_path_t *cpath;
  1319. extend_info_t *info = NULL;
  1320. smartlist_t *excludednodes;
  1321. tor_assert(head_ptr);
  1322. if (!*head_ptr) {
  1323. cur_len = 0;
  1324. } else {
  1325. cur_len = 1;
  1326. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1327. ++cur_len;
  1328. }
  1329. }
  1330. if (cur_len >= state->desired_path_len) {
  1331. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  1332. state->desired_path_len);
  1333. return 1;
  1334. }
  1335. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  1336. state->desired_path_len);
  1337. excludednodes = smartlist_create();
  1338. add_nickname_list_to_smartlist(excludednodes,get_options()->ExcludeNodes,0);
  1339. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1340. info = extend_info_dup(state->chosen_exit);
  1341. } else if (cur_len == 0) { /* picking first node */
  1342. routerinfo_t *r = choose_good_entry_server(state);
  1343. if (r)
  1344. info = extend_info_from_router(r);
  1345. } else {
  1346. routerinfo_t *r =
  1347. choose_good_middle_server(purpose, state, *head_ptr, cur_len);
  1348. if (r)
  1349. info = extend_info_from_router(r);
  1350. }
  1351. smartlist_free(excludednodes);
  1352. if (!info) {
  1353. log_fn(LOG_WARN,"Failed to find node for hop %d of our path. Discarding this circuit.", cur_len);
  1354. return -1;
  1355. }
  1356. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  1357. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1358. onion_append_hop(head_ptr, info);
  1359. extend_info_free(info);
  1360. return 0;
  1361. }
  1362. /** Create a new hop, annotate it with information about its
  1363. * corresponding router <b>choice</b>, and append it to the
  1364. * end of the cpath <b>head_ptr</b>. */
  1365. static int
  1366. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1367. {
  1368. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1369. /* link hop into the cpath, at the end. */
  1370. onion_append_to_cpath(head_ptr, hop);
  1371. hop->magic = CRYPT_PATH_MAGIC;
  1372. hop->state = CPATH_STATE_CLOSED;
  1373. hop->extend_info = extend_info_dup(choice);
  1374. hop->package_window = CIRCWINDOW_START;
  1375. hop->deliver_window = CIRCWINDOW_START;
  1376. return 0;
  1377. }
  1378. /** Allocate and return a new extend_info_t that can be used to build a
  1379. * circuit to or through the router <b>r</b>. */
  1380. extend_info_t *
  1381. extend_info_from_router(routerinfo_t *r)
  1382. {
  1383. extend_info_t *info;
  1384. tor_assert(r);
  1385. info = tor_malloc_zero(sizeof(extend_info_t));
  1386. strlcpy(info->nickname, r->nickname, sizeof(info->nickname));
  1387. memcpy(info->identity_digest, r->identity_digest, DIGEST_LEN);
  1388. info->onion_key = crypto_pk_dup_key(r->onion_pkey);
  1389. info->addr = r->addr;
  1390. info->port = r->or_port;
  1391. return info;
  1392. }
  1393. /** Release storage held by an extend_info_t struct. */
  1394. void
  1395. extend_info_free(extend_info_t *info)
  1396. {
  1397. tor_assert(info);
  1398. crypto_free_pk_env(info->onion_key);
  1399. tor_free(info);
  1400. }
  1401. /** Allocate and return a new extend_info_t with the same contents as
  1402. * <b>info</b>. */
  1403. extend_info_t *
  1404. extend_info_dup(extend_info_t *info)
  1405. {
  1406. extend_info_t *newinfo;
  1407. tor_assert(info);
  1408. newinfo = tor_malloc(sizeof(extend_info_t));
  1409. memcpy(newinfo, info, sizeof(extend_info_t));
  1410. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1411. return newinfo;
  1412. }
  1413. /**
  1414. * Return the routerinfo_t for the chosen exit router in <b>state</b>. If
  1415. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1416. * chosen exit, return NULL.
  1417. */
  1418. routerinfo_t *
  1419. build_state_get_exit_router(cpath_build_state_t *state)
  1420. {
  1421. if (!state || !state->chosen_exit)
  1422. return NULL;
  1423. return router_get_by_digest(state->chosen_exit->identity_digest);
  1424. }
  1425. /**
  1426. * Return the nickname for the chosen exit router in <b>state</b>. If
  1427. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1428. * chosen exit, return NULL.
  1429. */
  1430. const char *
  1431. build_state_get_exit_nickname(cpath_build_state_t *state)
  1432. {
  1433. if (!state || !state->chosen_exit)
  1434. return NULL;
  1435. return state->chosen_exit->nickname;
  1436. }
  1437. /** Return the number of helper nodes that we think are usable. */
  1438. static int
  1439. num_live_helpers(void)
  1440. {
  1441. int n = 0;
  1442. if (! helper_nodes)
  1443. return 0;
  1444. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1445. if (! helper->down_since && ! helper->unlisted_since)
  1446. ++n;);
  1447. return n;
  1448. }
  1449. /** If the use of helper nodes is configured, choose more helper nodes until
  1450. * we have enough in the list. */
  1451. static void
  1452. pick_helper_nodes(void)
  1453. {
  1454. or_options_t *options = get_options();
  1455. if (! options->UseHelperNodes)
  1456. return;
  1457. if (helper_nodes == NULL)
  1458. helper_nodes = smartlist_create();
  1459. while (smartlist_len(helper_nodes) < options->NumHelperNodes) {
  1460. routerinfo_t *entry = choose_good_entry_server(NULL);
  1461. /* XXXX deal with duplicate entries. */
  1462. helper_node_t *helper = tor_malloc_zero(sizeof(helper_node_t));
  1463. /* XXXX Downgrade this to info before release. */
  1464. log_fn(LOG_NOTICE, "Chose '%s' as helper node.", entry->nickname);
  1465. strlcpy(helper->nickname, entry->nickname, sizeof(helper->nickname));
  1466. memcpy(helper->identity, entry->identity_digest, DIGEST_LEN);
  1467. smartlist_add(helper_nodes, helper);
  1468. helper_nodes_changed();
  1469. }
  1470. }
  1471. /** Remove all elements from the list of helper nodes */
  1472. static void
  1473. clear_helper_nodes(void)
  1474. {
  1475. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h, tor_free(h));
  1476. smartlist_clear(helper_nodes);
  1477. helper_nodes_changed();
  1478. }
  1479. /** How long (in seconds) do we allow a helper node to be nonfunctional before
  1480. * we give up on it? */
  1481. #define HELPER_ALLOW_DOWNTIME 48*60*60
  1482. /** How long (in seconds) do we allow a helper node to be unlisted in the
  1483. * directory before we give up on it? */
  1484. #define HELPER_ALLOW_UNLISTED 48*60*60
  1485. /** Remove all helper nodes that have been down or unlisted for so long that
  1486. * we don't think they'll come up again. */
  1487. static void
  1488. remove_dead_helpers(void)
  1489. {
  1490. char dbuf[HEX_DIGEST_LEN+1];
  1491. char tbuf[ISO_TIME_LEN+1];
  1492. time_t now = time(NULL);
  1493. int i;
  1494. for (i = 0; i < smartlist_len(helper_nodes); ) {
  1495. helper_node_t *helper = smartlist_get(helper_nodes, i);
  1496. char *why = NULL;
  1497. time_t since = 0;
  1498. if (helper->unlisted_since + HELPER_ALLOW_UNLISTED > now) {
  1499. why = "unlisted";
  1500. since = helper->unlisted_since;
  1501. } else if (helper->down_since + HELPER_ALLOW_DOWNTIME > now) {
  1502. why = "down";
  1503. since = helper->unlisted_since;
  1504. }
  1505. if (why) {
  1506. base16_encode(dbuf, sizeof(dbuf), helper->identity, DIGEST_LEN);
  1507. format_local_iso_time(tbuf, since);
  1508. log_fn(LOG_WARN, "Helper node '%s' (%s) has been %s since %s; removing.",
  1509. helper->nickname, dbuf, why, tbuf);
  1510. tor_free(helper);
  1511. smartlist_del(helper_nodes, i);
  1512. helper_nodes_changed();
  1513. } else
  1514. ++i;
  1515. }
  1516. }
  1517. /** A new directory or router-status has arrived; update the down/listed status
  1518. * of the helper nodes.
  1519. *
  1520. * A helper is 'down' if the directory lists it as nonrunning, or if we tried
  1521. * to connect to it and failed. A helper is 'unlisted' if the directory
  1522. * doesn't include it.
  1523. */
  1524. void
  1525. helper_nodes_set_status_from_directory(void)
  1526. {
  1527. /* Don't call this on startup; only on a fresh download. Otherwise we'll
  1528. * think that things are unlisted. */
  1529. routerlist_t *routers;
  1530. time_t now;
  1531. int changed = 0;
  1532. if (! helper_nodes)
  1533. return;
  1534. router_get_routerlist(&routers);
  1535. if (! routers)
  1536. return;
  1537. now = time(NULL);
  1538. /*XXXX Most of these warns should be non-warns. */
  1539. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1540. {
  1541. routerinfo_t *r = router_get_by_digest(helper->identity);
  1542. if (! r) {
  1543. if (! helper->unlisted_since) {
  1544. /* Watch out for skew here. XXXX */
  1545. helper->unlisted_since = routers->published_on;
  1546. ++changed;
  1547. log_fn(LOG_WARN,"Helper node '%s' is not published in latest directory",
  1548. helper->nickname);
  1549. }
  1550. } else {
  1551. if (helper->unlisted_since) {
  1552. log_fn(LOG_WARN,"Helper node '%s' is listed again in latest directory",
  1553. helper->nickname);
  1554. ++changed;
  1555. }
  1556. helper->unlisted_since = 0;
  1557. if (! r->is_running) {
  1558. if (! helper->down_since) {
  1559. helper->down_since = now;
  1560. log_fn(LOG_WARN, "Helper node '%s' is now down.", helper->nickname);
  1561. ++changed;
  1562. }
  1563. } else {
  1564. if (helper->down_since) {
  1565. log_fn(LOG_WARN,"Helper node '%s' is up in latest directory",
  1566. helper->nickname);
  1567. ++changed;
  1568. }
  1569. helper->down_since = 0;
  1570. }
  1571. }
  1572. });
  1573. if (changed) {
  1574. log_fn(LOG_WARN, " (%d/%d helpers are usable)",
  1575. num_live_helpers(), smartlist_len(helper_nodes));
  1576. helper_nodes_changed();
  1577. }
  1578. remove_dead_helpers();
  1579. pick_helper_nodes();
  1580. }
  1581. /** Called when a connection to an OR with the identity digest <b>digest</b>
  1582. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  1583. * If the OR is a helper, change that helper's up/down status.
  1584. */
  1585. void
  1586. helper_node_set_status(const char *digest, int succeeded)
  1587. {
  1588. if (! helper_nodes)
  1589. return;
  1590. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1591. {
  1592. if (!memcmp(helper->identity, digest, DIGEST_LEN)) {
  1593. if (succeeded) {
  1594. if (helper->down_since) {
  1595. /*XXXX shouldn't warn. */
  1596. log_fn(LOG_WARN,
  1597. "Connection to formerly down helper node '%s' succeeded. "
  1598. "%d/%d helpers usable.", helper->nickname,
  1599. num_live_helpers(), smartlist_len(helper_nodes));
  1600. helper_nodes_changed();
  1601. }
  1602. helper->down_since = 0;
  1603. } else if (!helper->down_since) {
  1604. helper->down_since = time(NULL);
  1605. log_fn(LOG_WARN,
  1606. "Connection to helper node '%s' failed. %d/%d helpers usable.",
  1607. helper->nickname, num_live_helpers(), smartlist_len(helper_nodes));
  1608. helper_nodes_changed();
  1609. }
  1610. }
  1611. });
  1612. }
  1613. /** Pick a live (up and listed) helper node from the list of helpers. If
  1614. * no helpers are available, pick a new list. */
  1615. static routerinfo_t *
  1616. choose_random_helper(void)
  1617. {
  1618. smartlist_t *live_helpers = smartlist_create();
  1619. routerinfo_t *r;
  1620. if (! helper_nodes)
  1621. pick_helper_nodes();
  1622. retry:
  1623. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1624. if (! helper->down_since && ! helper->unlisted_since) {
  1625. if ((r = router_get_by_digest(helper->identity)))
  1626. smartlist_add(live_helpers, r);
  1627. });
  1628. if (! smartlist_len(live_helpers)) {
  1629. /* XXXX Is this right? What if network is down? */
  1630. log_fn(LOG_WARN, "No functional helper nodes found; picking a new set.");
  1631. clear_helper_nodes();
  1632. pick_helper_nodes();
  1633. goto retry;
  1634. }
  1635. r = smartlist_choose(live_helpers);
  1636. smartlist_free(live_helpers);
  1637. return r;
  1638. }
  1639. /** DOCDOC */
  1640. int
  1641. helper_nodes_parse_state(or_state_t *state, int set, const char **err)
  1642. {
  1643. helper_node_t *node = NULL;
  1644. smartlist_t *helpers = smartlist_create();
  1645. config_line_t *line;
  1646. *err = NULL;
  1647. for (line = state->HelperNodes; line; line = line->next) {
  1648. if (!strcasecmp(line->key, "HelperNode")) {
  1649. smartlist_t *args = smartlist_create();
  1650. node = tor_malloc_zero(sizeof(helper_node_t));
  1651. smartlist_add(helpers, node);
  1652. smartlist_split_string(args, line->value, " ",
  1653. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1654. if (smartlist_len(args)<2) {
  1655. *err = "Too few arguments to HelperNode";
  1656. break;
  1657. }
  1658. if (!is_legal_nickname(smartlist_get(args,0))) {
  1659. *err = "Bad nickname for HelperNode";
  1660. break;
  1661. }
  1662. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  1663. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  1664. strlen(smartlist_get(args,11)))<0) {
  1665. *err = "Bad hex digest for HelperNode";
  1666. break;
  1667. }
  1668. } else {
  1669. time_t when;
  1670. if (!node) {
  1671. *err = "HelperNodeDownSince/UnlistedSince without HelperNode";
  1672. break;
  1673. }
  1674. if (parse_iso_time(line->value, &when)<0) {
  1675. *err = "Bad time in HelperNodeDownSince/UnlistedSince";
  1676. break;
  1677. }
  1678. if (!strcasecmp(line->key, "HelperNodeDownSince"))
  1679. node->down_since = when;
  1680. else
  1681. node->unlisted_since = when;
  1682. }
  1683. }
  1684. if (*err || !set) {
  1685. SMARTLIST_FOREACH(helpers, helper_node_t *, h, tor_free(h));
  1686. smartlist_free(helpers);
  1687. }
  1688. if (!*err && set) {
  1689. if (helper_nodes) {
  1690. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h, tor_free(h));
  1691. smartlist_free(helper_nodes);
  1692. }
  1693. helper_nodes = helpers;
  1694. helper_nodes_dirty = 0;
  1695. }
  1696. return *err ? -1 : 0;
  1697. }
  1698. /** DOCDOC */
  1699. static void
  1700. helper_nodes_changed(void)
  1701. {
  1702. helper_nodes_dirty = 1;
  1703. or_state_save();
  1704. }
  1705. /** DOCDOC */
  1706. int
  1707. helper_nodes_update_state(or_state_t *state)
  1708. {
  1709. config_line_t **next, *line;
  1710. if (! helper_nodes_dirty)
  1711. return 0;
  1712. config_free_lines(state->HelperNodes);
  1713. next = &state->HelperNodes;
  1714. *next = NULL;
  1715. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h,
  1716. {
  1717. char dbuf[HEX_DIGEST_LEN+1];
  1718. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1719. line->key = tor_strdup("HelperNode");
  1720. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  1721. base16_encode(dbuf, sizeof(dbuf), h->identity, DIGEST_LEN);
  1722. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  1723. "%s %s", h->nickname, dbuf);
  1724. next = &(line->next);
  1725. if (h->down_since) {
  1726. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1727. line->key = tor_strdup("HelperNodeDownSince");
  1728. line->value = tor_malloc(ISO_TIME_LEN+1);
  1729. format_iso_time(line->value, h->down_since);
  1730. next = &(line->next);
  1731. }
  1732. if (h->unlisted_since) {
  1733. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1734. line->key = tor_strdup("HelperNodeUnlistedSince");
  1735. line->value = tor_malloc(ISO_TIME_LEN+1);
  1736. format_iso_time(line->value, h->unlisted_since);
  1737. next = &(line->next);
  1738. }
  1739. });
  1740. state->dirty = 1;
  1741. helper_nodes_dirty = 0;
  1742. return 1;
  1743. }