hs_common.c 40 KB

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