hs_common.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_common.c
  5. * \brief Contains code shared between different HS protocol version as well
  6. * as useful data structures and accessors used by other subsystems.
  7. * The rendcommon.c should only contains code relating to the v2
  8. * protocol.
  9. **/
  10. #define HS_COMMON_PRIVATE
  11. #include "or.h"
  12. #include "config.h"
  13. #include "networkstatus.h"
  14. #include "nodelist.h"
  15. #include "hs_cache.h"
  16. #include "hs_common.h"
  17. #include "hs_service.h"
  18. #include "rendcommon.h"
  19. #include "rendservice.h"
  20. #include "router.h"
  21. #include "shared_random.h"
  22. #include "shared_random_state.h"
  23. /* Ed25519 Basepoint value. Taken from section 5 of
  24. * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
  25. static const char *str_ed25519_basepoint =
  26. "(15112221349535400772501151409588531511"
  27. "454012693041857206046113283949847762202, "
  28. "463168356949264781694283940034751631413"
  29. "07993866256225615783033603165251855960)";
  30. #ifdef HAVE_SYS_UN_H
  31. /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
  32. * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
  33. * else return -ENOSYS if AF_UNIX is not supported (see function in the
  34. * #else statement below). */
  35. static int
  36. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  37. {
  38. tor_assert(ports);
  39. tor_assert(p);
  40. tor_assert(p->is_unix_addr);
  41. smartlist_add(ports, p);
  42. return 0;
  43. }
  44. /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
  45. * on success else return -ENOSYS if AF_UNIX is not supported (see function
  46. * in the #else statement below). */
  47. static int
  48. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  49. {
  50. tor_assert(conn);
  51. tor_assert(p);
  52. tor_assert(p->is_unix_addr);
  53. conn->base_.socket_family = AF_UNIX;
  54. tor_addr_make_unspec(&conn->base_.addr);
  55. conn->base_.port = 1;
  56. conn->base_.address = tor_strdup(p->unix_addr);
  57. return 0;
  58. }
  59. #else /* defined(HAVE_SYS_UN_H) */
  60. static int
  61. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  62. {
  63. (void) conn;
  64. (void) p;
  65. return -ENOSYS;
  66. }
  67. static int
  68. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  69. {
  70. (void) ports;
  71. (void) p;
  72. return -ENOSYS;
  73. }
  74. #endif /* HAVE_SYS_UN_H */
  75. /* Helper function: The key is a digest that we compare to a node_t object
  76. * current hsdir_index. */
  77. static int
  78. compare_digest_to_current_hsdir_index(const void *_key, const void **_member)
  79. {
  80. const char *key = _key;
  81. const node_t *node = *_member;
  82. return tor_memcmp(key, node->hsdir_index->current, DIGEST256_LEN);
  83. }
  84. /* Helper function: The key is a digest that we compare to a node_t object
  85. * next hsdir_index. */
  86. static int
  87. compare_digest_to_next_hsdir_index(const void *_key, const void **_member)
  88. {
  89. const char *key = _key;
  90. const node_t *node = *_member;
  91. return tor_memcmp(key, node->hsdir_index->next, DIGEST256_LEN);
  92. }
  93. /* Helper function: Compare two node_t objects current hsdir_index. */
  94. static int
  95. compare_node_current_hsdir_index(const void **a, const void **b)
  96. {
  97. const node_t *node1= *a;
  98. const node_t *node2 = *b;
  99. return tor_memcmp(node1->hsdir_index->current,
  100. node2->hsdir_index->current,
  101. DIGEST256_LEN);
  102. }
  103. /* Helper function: Compare two node_t objects next hsdir_index. */
  104. static int
  105. compare_node_next_hsdir_index(const void **a, const void **b)
  106. {
  107. const node_t *node1= *a;
  108. const node_t *node2 = *b;
  109. return tor_memcmp(node1->hsdir_index->next,
  110. node2->hsdir_index->next,
  111. DIGEST256_LEN);
  112. }
  113. /* Allocate and return a string containing the path to filename in directory.
  114. * This function will never return NULL. The caller must free this path. */
  115. char *
  116. hs_path_from_filename(const char *directory, const char *filename)
  117. {
  118. char *file_path = NULL;
  119. tor_assert(directory);
  120. tor_assert(filename);
  121. tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
  122. return file_path;
  123. }
  124. /* Make sure that the directory for <b>service</b> is private, using the config
  125. * <b>username</b>.
  126. * If <b>create</b> is true:
  127. * - if the directory exists, change permissions if needed,
  128. * - if the directory does not exist, create it with the correct permissions.
  129. * If <b>create</b> is false:
  130. * - if the directory exists, check permissions,
  131. * - if the directory does not exist, check if we think we can create it.
  132. * Return 0 on success, -1 on failure. */
  133. int
  134. hs_check_service_private_dir(const char *username, const char *path,
  135. unsigned int dir_group_readable,
  136. unsigned int create)
  137. {
  138. cpd_check_t check_opts = CPD_NONE;
  139. tor_assert(path);
  140. if (create) {
  141. check_opts |= CPD_CREATE;
  142. } else {
  143. check_opts |= CPD_CHECK_MODE_ONLY;
  144. check_opts |= CPD_CHECK;
  145. }
  146. if (dir_group_readable) {
  147. check_opts |= CPD_GROUP_READ;
  148. }
  149. /* Check/create directory */
  150. if (check_private_dir(path, check_opts, username) < 0) {
  151. return -1;
  152. }
  153. return 0;
  154. }
  155. /** Get the default HS time period length in minutes from the consensus. */
  156. STATIC uint64_t
  157. get_time_period_length(void)
  158. {
  159. int32_t time_period_length = networkstatus_get_param(NULL, "hsdir-interval",
  160. HS_TIME_PERIOD_LENGTH_DEFAULT,
  161. HS_TIME_PERIOD_LENGTH_MIN,
  162. HS_TIME_PERIOD_LENGTH_MAX);
  163. /* Make sure it's a positive value. */
  164. tor_assert(time_period_length >= 0);
  165. /* uint64_t will always be able to contain a int32_t */
  166. return (uint64_t) time_period_length;
  167. }
  168. /** Get the HS time period number at time <b>now</b> */
  169. uint64_t
  170. hs_get_time_period_num(time_t now)
  171. {
  172. uint64_t time_period_num;
  173. /* Start by calculating minutes since the epoch */
  174. uint64_t time_period_length = get_time_period_length();
  175. uint64_t minutes_since_epoch = now / 60;
  176. /* Apply the rotation offset as specified by prop224 (section
  177. * [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
  178. * publication */
  179. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  180. time_period_rotation_offset /= 60; /* go from seconds to minutes */
  181. tor_assert(minutes_since_epoch > time_period_rotation_offset);
  182. minutes_since_epoch -= time_period_rotation_offset;
  183. /* Calculate the time period */
  184. time_period_num = minutes_since_epoch / time_period_length;
  185. return time_period_num;
  186. }
  187. /** Get the number of the _upcoming_ HS time period, given that the current
  188. * time is <b>now</b>. */
  189. uint64_t
  190. hs_get_next_time_period_num(time_t now)
  191. {
  192. return hs_get_time_period_num(now) + 1;
  193. }
  194. /* Return the start time of the upcoming time period based on <b>now</b>. */
  195. time_t
  196. hs_get_start_time_of_next_time_period(time_t now)
  197. {
  198. uint64_t time_period_length = get_time_period_length();
  199. /* Get start time of next time period */
  200. uint64_t next_time_period_num = hs_get_next_time_period_num(now);
  201. uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
  202. /* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
  203. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  204. return start_of_next_tp_in_mins * 60 + time_period_rotation_offset;
  205. }
  206. /* Create a new rend_data_t for a specific given <b>version</b>.
  207. * Return a pointer to the newly allocated data structure. */
  208. static rend_data_t *
  209. rend_data_alloc(uint32_t version)
  210. {
  211. rend_data_t *rend_data = NULL;
  212. switch (version) {
  213. case HS_VERSION_TWO:
  214. {
  215. rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
  216. v2->base_.version = HS_VERSION_TWO;
  217. v2->base_.hsdirs_fp = smartlist_new();
  218. rend_data = &v2->base_;
  219. break;
  220. }
  221. default:
  222. tor_assert(0);
  223. break;
  224. }
  225. return rend_data;
  226. }
  227. /** Free all storage associated with <b>data</b> */
  228. void
  229. rend_data_free(rend_data_t *data)
  230. {
  231. if (!data) {
  232. return;
  233. }
  234. /* By using our allocation function, this should always be set. */
  235. tor_assert(data->hsdirs_fp);
  236. /* Cleanup the HSDir identity digest. */
  237. SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
  238. smartlist_free(data->hsdirs_fp);
  239. /* Depending on the version, cleanup. */
  240. switch (data->version) {
  241. case HS_VERSION_TWO:
  242. {
  243. rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
  244. tor_free(v2_data);
  245. break;
  246. }
  247. default:
  248. tor_assert(0);
  249. }
  250. }
  251. /* Allocate and return a deep copy of <b>data</b>. */
  252. rend_data_t *
  253. rend_data_dup(const rend_data_t *data)
  254. {
  255. rend_data_t *data_dup = NULL;
  256. smartlist_t *hsdirs_fp = smartlist_new();
  257. tor_assert(data);
  258. tor_assert(data->hsdirs_fp);
  259. SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
  260. smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
  261. switch (data->version) {
  262. case HS_VERSION_TWO:
  263. {
  264. rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
  265. sizeof(*v2_data));
  266. data_dup = &v2_data->base_;
  267. data_dup->hsdirs_fp = hsdirs_fp;
  268. break;
  269. }
  270. default:
  271. tor_assert(0);
  272. break;
  273. }
  274. return data_dup;
  275. }
  276. /* Compute the descriptor ID for each HS descriptor replica and save them. A
  277. * valid onion address must be present in the <b>rend_data</b>.
  278. *
  279. * Return 0 on success else -1. */
  280. static int
  281. compute_desc_id(rend_data_t *rend_data)
  282. {
  283. int ret = 0;
  284. unsigned replica;
  285. time_t now = time(NULL);
  286. tor_assert(rend_data);
  287. switch (rend_data->version) {
  288. case HS_VERSION_TWO:
  289. {
  290. rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  291. /* Compute descriptor ID for each replicas. */
  292. for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
  293. replica++) {
  294. ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
  295. v2_data->onion_address,
  296. v2_data->descriptor_cookie,
  297. now, replica);
  298. if (ret < 0) {
  299. goto end;
  300. }
  301. }
  302. break;
  303. }
  304. default:
  305. tor_assert(0);
  306. }
  307. end:
  308. return ret;
  309. }
  310. /* Allocate and initialize a rend_data_t object for a service using the
  311. * provided arguments. All arguments are optional (can be NULL), except from
  312. * <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
  313. * the service private key. The <b>cookie</b> is the rendezvous cookie and
  314. * <b>auth_type</b> is which authentiation this service is configured with.
  315. *
  316. * Return a valid rend_data_t pointer. This only returns a version 2 object of
  317. * rend_data_t. */
  318. rend_data_t *
  319. rend_data_service_create(const char *onion_address, const char *pk_digest,
  320. const uint8_t *cookie, rend_auth_type_t auth_type)
  321. {
  322. /* Create a rend_data_t object for version 2. */
  323. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  324. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  325. /* We need at least one else the call is wrong. */
  326. tor_assert(onion_address != NULL);
  327. if (pk_digest) {
  328. memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
  329. }
  330. if (cookie) {
  331. memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
  332. }
  333. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  334. v2->auth_type = auth_type;
  335. return rend_data;
  336. }
  337. /* Allocate and initialize a rend_data_t object for a client request using the
  338. * given arguments. Either an onion address or a descriptor ID is needed. Both
  339. * can be given but in this case only the onion address will be used to make
  340. * the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
  341. * <b>auth_type</b> is which authentiation the service is configured with.
  342. *
  343. * Return a valid rend_data_t pointer or NULL on error meaning the
  344. * descriptor IDs couldn't be computed from the given data. */
  345. rend_data_t *
  346. rend_data_client_create(const char *onion_address, const char *desc_id,
  347. const char *cookie, rend_auth_type_t auth_type)
  348. {
  349. /* Create a rend_data_t object for version 2. */
  350. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  351. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  352. /* We need at least one else the call is wrong. */
  353. tor_assert(onion_address != NULL || desc_id != NULL);
  354. if (cookie) {
  355. memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
  356. }
  357. if (desc_id) {
  358. memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
  359. }
  360. if (onion_address) {
  361. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  362. if (compute_desc_id(rend_data) < 0) {
  363. goto error;
  364. }
  365. }
  366. v2->auth_type = auth_type;
  367. return rend_data;
  368. error:
  369. rend_data_free(rend_data);
  370. return NULL;
  371. }
  372. /* Return the onion address from the rend data. Depending on the version,
  373. * the size of the address can vary but it's always NUL terminated. */
  374. const char *
  375. rend_data_get_address(const rend_data_t *rend_data)
  376. {
  377. tor_assert(rend_data);
  378. switch (rend_data->version) {
  379. case HS_VERSION_TWO:
  380. return TO_REND_DATA_V2(rend_data)->onion_address;
  381. default:
  382. /* We should always have a supported version. */
  383. tor_assert(0);
  384. }
  385. }
  386. /* Return the descriptor ID for a specific replica number from the rend
  387. * data. The returned data is a binary digest and depending on the version its
  388. * size can vary. The size of the descriptor ID is put in <b>len_out</b> if
  389. * non NULL. */
  390. const char *
  391. rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
  392. size_t *len_out)
  393. {
  394. tor_assert(rend_data);
  395. switch (rend_data->version) {
  396. case HS_VERSION_TWO:
  397. tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
  398. if (len_out) {
  399. *len_out = DIGEST_LEN;
  400. }
  401. return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
  402. default:
  403. /* We should always have a supported version. */
  404. tor_assert(0);
  405. }
  406. }
  407. /* Return the public key digest using the given <b>rend_data</b>. The size of
  408. * the digest is put in <b>len_out</b> (if set) which can differ depending on
  409. * the version. */
  410. const uint8_t *
  411. rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
  412. {
  413. tor_assert(rend_data);
  414. switch (rend_data->version) {
  415. case HS_VERSION_TWO:
  416. {
  417. const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  418. if (len_out) {
  419. *len_out = sizeof(v2_data->rend_pk_digest);
  420. }
  421. return (const uint8_t *) v2_data->rend_pk_digest;
  422. }
  423. default:
  424. /* We should always have a supported version. */
  425. tor_assert(0);
  426. }
  427. }
  428. /* Using the given time period number, compute the disaster shared random
  429. * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
  430. static void
  431. get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  432. {
  433. crypto_digest_t *digest;
  434. tor_assert(srv_out);
  435. digest = crypto_digest256_new(DIGEST_SHA3_256);
  436. /* Setup payload: H("shared-random-disaster" | INT_8(period_num)) */
  437. crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
  438. HS_SRV_DISASTER_PREFIX_LEN);
  439. crypto_digest_add_bytes(digest, (const char *) &time_period_num,
  440. sizeof(time_period_num));
  441. crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
  442. crypto_digest_free(digest);
  443. }
  444. /* When creating a blinded key, we need a parameter which construction is as
  445. * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
  446. *
  447. * The nonce has a pre-defined format which uses the time period number
  448. * period_num and the start of the period in second start_time_period.
  449. *
  450. * The secret of size secret_len is optional meaning that it can be NULL and
  451. * thus will be ignored for the param construction.
  452. *
  453. * The result is put in param_out. */
  454. static void
  455. build_blinded_key_param(const ed25519_public_key_t *pubkey,
  456. const uint8_t *secret, size_t secret_len,
  457. uint64_t period_num, uint64_t start_time_period,
  458. uint8_t *param_out)
  459. {
  460. size_t offset = 0;
  461. uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
  462. crypto_digest_t *digest;
  463. tor_assert(pubkey);
  464. tor_assert(param_out);
  465. /* Create the nonce N. The construction is as follow:
  466. * N = "key-blind" || INT_8(period_num) || INT_8(start_period_sec) */
  467. memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
  468. offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
  469. set_uint64(nonce + offset, period_num);
  470. offset += sizeof(uint64_t);
  471. set_uint64(nonce + offset, start_time_period);
  472. offset += sizeof(uint64_t);
  473. tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
  474. /* Generate the parameter h and the construction is as follow:
  475. * h = H(pubkey | [secret] | ed25519-basepoint | nonce) */
  476. digest = crypto_digest256_new(DIGEST_SHA3_256);
  477. crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
  478. /* Optional secret. */
  479. if (secret) {
  480. crypto_digest_add_bytes(digest, (char *) secret, secret_len);
  481. }
  482. crypto_digest_add_bytes(digest, str_ed25519_basepoint,
  483. strlen(str_ed25519_basepoint));
  484. crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
  485. /* Extract digest and put it in the param. */
  486. crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
  487. crypto_digest_free(digest);
  488. }
  489. /* Using an ed25519 public key and version to build the checksum of an
  490. * address. Put in checksum_out. Format is:
  491. * SHA3-256(".onion checksum" || PUBKEY || VERSION)
  492. *
  493. * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
  494. static void
  495. build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
  496. uint8_t *checksum_out)
  497. {
  498. size_t offset = 0;
  499. char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
  500. /* Build checksum data. */
  501. memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
  502. HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
  503. offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
  504. memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
  505. offset += ED25519_PUBKEY_LEN;
  506. set_uint8(data + offset, version);
  507. offset += sizeof(version);
  508. tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
  509. /* Hash the data payload to create the checksum. */
  510. crypto_digest256((char *) checksum_out, data, sizeof(data),
  511. DIGEST_SHA3_256);
  512. }
  513. /* Using an ed25519 public key, checksum and version to build the binary
  514. * representation of a service address. Put in addr_out. Format is:
  515. * addr_out = PUBKEY || CHECKSUM || VERSION
  516. *
  517. * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
  518. static void
  519. build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
  520. uint8_t version, char *addr_out)
  521. {
  522. size_t offset = 0;
  523. tor_assert(key);
  524. tor_assert(checksum);
  525. memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
  526. offset += ED25519_PUBKEY_LEN;
  527. memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  528. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  529. set_uint8(addr_out + offset, version);
  530. offset += sizeof(uint8_t);
  531. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  532. }
  533. /* Helper for hs_parse_address(): Using a binary representation of a service
  534. * address, parse its content into the key_out, checksum_out and version_out.
  535. * Any out variable can be NULL in case the caller would want only one field.
  536. * checksum_out MUST at least be 2 bytes long. address must be at least
  537. * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
  538. static void
  539. hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
  540. uint8_t *checksum_out, uint8_t *version_out)
  541. {
  542. size_t offset = 0;
  543. tor_assert(address);
  544. if (key_out) {
  545. /* First is the key. */
  546. memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
  547. }
  548. offset += ED25519_PUBKEY_LEN;
  549. if (checksum_out) {
  550. /* Followed by a 2 bytes checksum. */
  551. memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  552. }
  553. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  554. if (version_out) {
  555. /* Finally, version value is 1 byte. */
  556. *version_out = get_uint8(address + offset);
  557. }
  558. offset += sizeof(uint8_t);
  559. /* Extra safety. */
  560. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  561. }
  562. /* Using the given identity public key and a blinded public key, compute the
  563. * subcredential and put it in subcred_out. This can't fail. */
  564. void
  565. hs_get_subcredential(const ed25519_public_key_t *identity_pk,
  566. const ed25519_public_key_t *blinded_pk,
  567. uint8_t *subcred_out)
  568. {
  569. uint8_t credential[DIGEST256_LEN];
  570. crypto_digest_t *digest;
  571. tor_assert(identity_pk);
  572. tor_assert(blinded_pk);
  573. tor_assert(subcred_out);
  574. /* First, build the credential. Construction is as follow:
  575. * credential = H("credential" | public-identity-key) */
  576. digest = crypto_digest256_new(DIGEST_SHA3_256);
  577. crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
  578. HS_CREDENTIAL_PREFIX_LEN);
  579. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  580. ED25519_PUBKEY_LEN);
  581. crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
  582. crypto_digest_free(digest);
  583. /* Now, compute the subcredential. Construction is as follow:
  584. * subcredential = H("subcredential" | credential | blinded-public-key). */
  585. digest = crypto_digest256_new(DIGEST_SHA3_256);
  586. crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
  587. HS_SUBCREDENTIAL_PREFIX_LEN);
  588. crypto_digest_add_bytes(digest, (const char *) credential,
  589. sizeof(credential));
  590. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  591. ED25519_PUBKEY_LEN);
  592. crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
  593. crypto_digest_free(digest);
  594. }
  595. /* From the given list of hidden service ports, find the matching one from the
  596. * given edge connection conn and set the connection address from the service
  597. * port object. Return 0 on success or -1 if none. */
  598. int
  599. hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
  600. {
  601. rend_service_port_config_t *chosen_port;
  602. unsigned int warn_once = 0;
  603. smartlist_t *matching_ports;
  604. tor_assert(ports);
  605. tor_assert(conn);
  606. matching_ports = smartlist_new();
  607. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  608. if (TO_CONN(conn)->port != p->virtual_port) {
  609. continue;
  610. }
  611. if (!(p->is_unix_addr)) {
  612. smartlist_add(matching_ports, p);
  613. } else {
  614. if (add_unix_port(matching_ports, p)) {
  615. if (!warn_once) {
  616. /* Unix port not supported so warn only once. */
  617. log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
  618. "which is unsupported on this platform. "
  619. "Ignoring it.",
  620. TO_CONN(conn)->port);
  621. }
  622. warn_once++;
  623. }
  624. }
  625. } SMARTLIST_FOREACH_END(p);
  626. chosen_port = smartlist_choose(matching_ports);
  627. smartlist_free(matching_ports);
  628. if (chosen_port) {
  629. if (!(chosen_port->is_unix_addr)) {
  630. /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
  631. tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
  632. TO_CONN(conn)->port = chosen_port->real_port;
  633. } else {
  634. if (set_unix_port(conn, chosen_port)) {
  635. /* Simply impossible to end up here else we were able to add a Unix
  636. * port without AF_UNIX support... ? */
  637. tor_assert(0);
  638. }
  639. }
  640. }
  641. return (chosen_port) ? 0 : -1;
  642. }
  643. /* Using a base32 representation of a service address, parse its content into
  644. * the key_out, checksum_out and version_out. Any out variable can be NULL in
  645. * case the caller would want only one field. checksum_out MUST at least be 2
  646. * bytes long.
  647. *
  648. * Return 0 if parsing went well; return -1 in case of error. */
  649. int
  650. hs_parse_address(const char *address, ed25519_public_key_t *key_out,
  651. uint8_t *checksum_out, uint8_t *version_out)
  652. {
  653. char decoded[HS_SERVICE_ADDR_LEN];
  654. tor_assert(address);
  655. /* Obvious length check. */
  656. if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
  657. log_warn(LD_REND, "Service address %s has an invalid length. "
  658. "Expected %lu but got %lu.",
  659. escaped_safe_str(address),
  660. (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
  661. (unsigned long) strlen(address));
  662. goto invalid;
  663. }
  664. /* Decode address so we can extract needed fields. */
  665. if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
  666. log_warn(LD_REND, "Service address %s can't be decoded.",
  667. escaped_safe_str(address));
  668. goto invalid;
  669. }
  670. /* Parse the decoded address into the fields we need. */
  671. hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
  672. return 0;
  673. invalid:
  674. return -1;
  675. }
  676. /* Validate a given onion address. The length, the base32 decoding and
  677. * checksum are validated. Return 1 if valid else 0. */
  678. int
  679. hs_address_is_valid(const char *address)
  680. {
  681. uint8_t version;
  682. uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
  683. uint8_t target_checksum[DIGEST256_LEN];
  684. ed25519_public_key_t key;
  685. /* Parse the decoded address into the fields we need. */
  686. if (hs_parse_address(address, &key, checksum, &version) < 0) {
  687. goto invalid;
  688. }
  689. /* Get the checksum it's suppose to be and compare it with what we have
  690. * encoded in the address. */
  691. build_hs_checksum(&key, version, target_checksum);
  692. if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
  693. log_warn(LD_REND, "Service address %s invalid checksum.",
  694. escaped_safe_str(address));
  695. goto invalid;
  696. }
  697. /* Valid address. */
  698. return 1;
  699. invalid:
  700. return 0;
  701. }
  702. /* Build a service address using an ed25519 public key and a given version.
  703. * The returned address is base32 encoded and put in addr_out. The caller MUST
  704. * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
  705. *
  706. * Format is as follow:
  707. * base32(PUBKEY || CHECKSUM || VERSION)
  708. * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
  709. * */
  710. void
  711. hs_build_address(const ed25519_public_key_t *key, uint8_t version,
  712. char *addr_out)
  713. {
  714. uint8_t checksum[DIGEST256_LEN];
  715. char address[HS_SERVICE_ADDR_LEN];
  716. tor_assert(key);
  717. tor_assert(addr_out);
  718. /* Get the checksum of the address. */
  719. build_hs_checksum(key, version, checksum);
  720. /* Get the binary address representation. */
  721. build_hs_address(key, checksum, version, address);
  722. /* Encode the address. addr_out will be NUL terminated after this. */
  723. base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
  724. sizeof(address));
  725. /* Validate what we just built. */
  726. tor_assert(hs_address_is_valid(addr_out));
  727. }
  728. /* Return a newly allocated copy of lspec. */
  729. link_specifier_t *
  730. hs_link_specifier_dup(const link_specifier_t *lspec)
  731. {
  732. link_specifier_t *dup = link_specifier_new();
  733. memcpy(dup, lspec, sizeof(*dup));
  734. /* The unrecognized field is a dynamic array so make sure to copy its
  735. * content and not the pointer. */
  736. link_specifier_setlen_un_unrecognized(
  737. dup, link_specifier_getlen_un_unrecognized(lspec));
  738. if (link_specifier_getlen_un_unrecognized(dup)) {
  739. memcpy(link_specifier_getarray_un_unrecognized(dup),
  740. link_specifier_getconstarray_un_unrecognized(lspec),
  741. link_specifier_getlen_un_unrecognized(dup));
  742. }
  743. return dup;
  744. }
  745. /* From a given ed25519 public key pk and an optional secret, compute a
  746. * blinded public key and put it in blinded_pk_out. This is only useful to
  747. * the client side because the client only has access to the identity public
  748. * key of the service. */
  749. void
  750. hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
  751. const uint8_t *secret, size_t secret_len,
  752. uint64_t time_period_num,
  753. ed25519_public_key_t *blinded_pk_out)
  754. {
  755. /* Our blinding key API requires a 32 bytes parameter. */
  756. uint8_t param[DIGEST256_LEN];
  757. tor_assert(pk);
  758. tor_assert(blinded_pk_out);
  759. tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
  760. build_blinded_key_param(pk, secret, secret_len,
  761. time_period_num, get_time_period_length(), param);
  762. ed25519_public_blind(blinded_pk_out, pk, param);
  763. }
  764. /* From a given ed25519 keypair kp and an optional secret, compute a blinded
  765. * keypair for the current time period and put it in blinded_kp_out. This is
  766. * only useful by the service side because the client doesn't have access to
  767. * the identity secret key. */
  768. void
  769. hs_build_blinded_keypair(const ed25519_keypair_t *kp,
  770. const uint8_t *secret, size_t secret_len,
  771. uint64_t time_period_num,
  772. ed25519_keypair_t *blinded_kp_out)
  773. {
  774. /* Our blinding key API requires a 32 bytes parameter. */
  775. uint8_t param[DIGEST256_LEN];
  776. tor_assert(kp);
  777. tor_assert(blinded_kp_out);
  778. /* Extra safety. A zeroed key is bad. */
  779. tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
  780. tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
  781. build_blinded_key_param(&kp->pubkey, secret, secret_len,
  782. time_period_num, get_time_period_length(), param);
  783. ed25519_keypair_blind(blinded_kp_out, kp, param);
  784. }
  785. /* Return true if overlap mode is active given the date in consensus. If
  786. * consensus is NULL, then we use the latest live consensus we can find. */
  787. MOCK_IMPL(int,
  788. hs_overlap_mode_is_active, (const networkstatus_t *consensus, time_t now))
  789. {
  790. struct tm valid_after_tm;
  791. if (!consensus) {
  792. consensus = networkstatus_get_live_consensus(now);
  793. if (!consensus) {
  794. return 0;
  795. }
  796. }
  797. /* XXX: Futur commits will change this to a slot system so it can be
  798. * fine tuned better for testing networks in terms of timings. */
  799. /* From the spec: "Specifically, when a hidden service fetches a consensus
  800. * with "valid-after" between 00:00UTC and 12:00UTC, it goes into
  801. * "descriptor overlap" mode." */
  802. tor_gmtime_r(&consensus->valid_after, &valid_after_tm);
  803. if (valid_after_tm.tm_hour > 0 && valid_after_tm.tm_hour < 12) {
  804. return 1;
  805. }
  806. return 0;
  807. }
  808. /* Return 1 if any virtual port in ports needs a circuit with good uptime.
  809. * Else return 0. */
  810. int
  811. hs_service_requires_uptime_circ(const smartlist_t *ports)
  812. {
  813. tor_assert(ports);
  814. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  815. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  816. p->virtual_port)) {
  817. return 1;
  818. }
  819. } SMARTLIST_FOREACH_END(p);
  820. return 0;
  821. }
  822. /* Build hs_index which is used to find the responsible hsdirs. This index
  823. * value is used to select the responsible HSDir where their hsdir_index is
  824. * closest to this value.
  825. * SHA3-256("store-at-idx" | blinded_public_key |
  826. * INT_8(replicanum) | INT_8(period_num) )
  827. *
  828. * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
  829. void
  830. hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
  831. uint64_t period_num, uint8_t *hs_index_out)
  832. {
  833. crypto_digest_t *digest;
  834. tor_assert(blinded_pk);
  835. tor_assert(hs_index_out);
  836. /* Build hs_index. See construction at top of function comment. */
  837. digest = crypto_digest256_new(DIGEST_SHA3_256);
  838. crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
  839. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  840. ED25519_PUBKEY_LEN);
  841. crypto_digest_add_bytes(digest, (const char *) &replica, sizeof(replica));
  842. crypto_digest_add_bytes(digest, (const char *) &period_num,
  843. sizeof(period_num));
  844. crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
  845. crypto_digest_free(digest);
  846. }
  847. /* Build hsdir_index which is used to find the responsible hsdirs. This is the
  848. * index value that is compare to the hs_index when selecting an HSDir.
  849. * SHA3-256("node-idx" | node_identity |
  850. * shared_random_value | INT_8(period_num) )
  851. *
  852. * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
  853. void
  854. hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
  855. const uint8_t *srv_value, uint64_t period_num,
  856. uint8_t *hsdir_index_out)
  857. {
  858. crypto_digest_t *digest;
  859. tor_assert(identity_pk);
  860. tor_assert(srv_value);
  861. tor_assert(hsdir_index_out);
  862. /* Build hsdir_index. See construction at top of function comment. */
  863. digest = crypto_digest256_new(DIGEST_SHA3_256);
  864. crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
  865. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  866. ED25519_PUBKEY_LEN);
  867. crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
  868. crypto_digest_add_bytes(digest, (const char *) &period_num,
  869. sizeof(period_num));
  870. crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
  871. crypto_digest_free(digest);
  872. }
  873. /* Return a newly allocated buffer containing the current shared random value
  874. * or if not present, a disaster value is computed using the given time period
  875. * number. This function can't fail. */
  876. uint8_t *
  877. hs_get_current_srv(uint64_t time_period_num)
  878. {
  879. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  880. const sr_srv_t *current_srv = sr_get_current();
  881. if (current_srv) {
  882. memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
  883. } else {
  884. /* Disaster mode. */
  885. get_disaster_srv(time_period_num, sr_value);
  886. }
  887. return sr_value;
  888. }
  889. /* Return a newly allocated buffer containing the previous shared random
  890. * value or if not present, a disaster value is computed using the given time
  891. * period number. This function can't fail. */
  892. uint8_t *
  893. hs_get_previous_srv(uint64_t time_period_num)
  894. {
  895. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  896. const sr_srv_t *previous_srv = sr_get_previous();
  897. if (previous_srv) {
  898. memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
  899. } else {
  900. /* Disaster mode. */
  901. get_disaster_srv(time_period_num, sr_value);
  902. }
  903. return sr_value;
  904. }
  905. /* Return the number of replicas defined by a consensus parameter or the
  906. * default value. */
  907. int32_t
  908. hs_get_hsdir_n_replicas(void)
  909. {
  910. /* The [1,16] range is a specification requirement. */
  911. return networkstatus_get_param(NULL, "hsdir_n_replicas",
  912. HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
  913. }
  914. /* Return the spread fetch value defined by a consensus parameter or the
  915. * default value. */
  916. int32_t
  917. hs_get_hsdir_spread_fetch(void)
  918. {
  919. /* The [1,128] range is a specification requirement. */
  920. return networkstatus_get_param(NULL, "hsdir_spread_fetch",
  921. HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
  922. }
  923. /* Return the spread store value defined by a consensus parameter or the
  924. * default value. */
  925. int32_t
  926. hs_get_hsdir_spread_store(void)
  927. {
  928. /* The [1,128] range is a specification requirement. */
  929. return networkstatus_get_param(NULL, "hsdir_spread_store",
  930. HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
  931. }
  932. /* For a given blinded key and time period number, get the responsible HSDir
  933. * and put their routerstatus_t object in the responsible_dirs list. If
  934. * is_next_period is true, the next hsdir_index of the node_t is used. If
  935. * is_client is true, the spread fetch consensus parameter is used else the
  936. * spread store is used which is only for upload. This function can't fail but
  937. * it is possible that the responsible_dirs list contains fewer nodes than
  938. * expected.
  939. *
  940. * This function goes over the latest consensus routerstatus list and sorts it
  941. * by their node_t hsdir_index then does a binary search to find the closest
  942. * node. All of this makes it a bit CPU intensive so use it wisely. */
  943. void
  944. hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
  945. uint64_t time_period_num, int is_next_period,
  946. int is_client, smartlist_t *responsible_dirs)
  947. {
  948. smartlist_t *sorted_nodes;
  949. /* The compare function used for the smartlist bsearch. We have two
  950. * different depending on is_next_period. */
  951. int (*cmp_fct)(const void *, const void **);
  952. tor_assert(blinded_pk);
  953. tor_assert(responsible_dirs);
  954. sorted_nodes = smartlist_new();
  955. /* Add every node_t that support HSDir v3 for which we do have a valid
  956. * hsdir_index already computed for them for this consensus. */
  957. {
  958. networkstatus_t *c = networkstatus_get_latest_consensus();
  959. if (!c || smartlist_len(c->routerstatus_list) == 0) {
  960. log_warn(LD_REND, "No valid consensus so we can't get the responsible "
  961. "hidden service directories.");
  962. goto done;
  963. }
  964. SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
  965. /* Even though this node_t object won't be modified and should be const,
  966. * we can't add const object in a smartlist_t. */
  967. node_t *n = node_get_mutable_by_id(rs->identity_digest);
  968. tor_assert(n);
  969. if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
  970. if (BUG(n->hsdir_index == NULL)) {
  971. continue;
  972. }
  973. smartlist_add(sorted_nodes, n);
  974. }
  975. } SMARTLIST_FOREACH_END(rs);
  976. }
  977. if (smartlist_len(sorted_nodes) == 0) {
  978. log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
  979. goto done;
  980. }
  981. /* First thing we have to do is sort all node_t by hsdir_index. The
  982. * is_next_period tells us if we want the current or the next one. Set the
  983. * bsearch compare function also while we are at it. */
  984. if (is_next_period) {
  985. smartlist_sort(sorted_nodes, compare_node_next_hsdir_index);
  986. cmp_fct = compare_digest_to_next_hsdir_index;
  987. } else {
  988. smartlist_sort(sorted_nodes, compare_node_current_hsdir_index);
  989. cmp_fct = compare_digest_to_current_hsdir_index;
  990. }
  991. /* For all replicas, we'll select a set of HSDirs using the consensus
  992. * parameters and the sorted list. The replica starting at value 1 is
  993. * defined by the specification. */
  994. for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
  995. int idx, start, found, n_added = 0;
  996. uint8_t hs_index[DIGEST256_LEN] = {0};
  997. /* Number of node to add to the responsible dirs list depends on if we are
  998. * trying to fetch or store. A client always fetches. */
  999. int n_to_add = (is_client) ? hs_get_hsdir_spread_fetch() :
  1000. hs_get_hsdir_spread_store();
  1001. /* Get the index that we should use to select the node. */
  1002. hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
  1003. /* The compare function pointer has been set correctly earlier. */
  1004. start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
  1005. &found);
  1006. /* Getting the length of the list if no member is greater than the key we
  1007. * are looking for so start at the first element. */
  1008. if (idx == smartlist_len(sorted_nodes)) {
  1009. start = idx = 0;
  1010. }
  1011. while (n_added < n_to_add) {
  1012. const node_t *node = smartlist_get(sorted_nodes, idx);
  1013. /* If the node has already been selected which is possible between
  1014. * replicas, the specification says to skip over. */
  1015. if (!smartlist_contains(responsible_dirs, node->rs)) {
  1016. smartlist_add(responsible_dirs, node->rs);
  1017. ++n_added;
  1018. }
  1019. if (++idx == smartlist_len(sorted_nodes)) {
  1020. /* Wrap if we've reached the end of the list. */
  1021. idx = 0;
  1022. }
  1023. if (idx == start) {
  1024. /* We've gone over the whole list, stop and avoid infinite loop. */
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. done:
  1030. smartlist_free(sorted_nodes);
  1031. }
  1032. /* Initialize the entire HS subsytem. This is called in tor_init() before any
  1033. * torrc options are loaded. Only for >= v3. */
  1034. void
  1035. hs_init(void)
  1036. {
  1037. hs_circuitmap_init();
  1038. hs_service_init();
  1039. hs_cache_init();
  1040. }
  1041. /* Release and cleanup all memory of the HS subsystem (all version). This is
  1042. * called by tor_free_all(). */
  1043. void
  1044. hs_free_all(void)
  1045. {
  1046. hs_circuitmap_free_all();
  1047. hs_service_free_all();
  1048. hs_cache_free_all();
  1049. }