shared_random_state.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /* Copyright (c) 2016, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file shared_random_state.c
  5. *
  6. * \brief Functions and data structures for the state of the random protocol
  7. * as defined in proposal #250.
  8. **/
  9. #define SHARED_RANDOM_STATE_PRIVATE
  10. #include "or.h"
  11. #include "shared_random.h"
  12. #include "config.h"
  13. #include "confparse.h"
  14. #include "dirvote.h"
  15. #include "networkstatus.h"
  16. #include "router.h"
  17. #include "shared_random_state.h"
  18. /* Default filename of the shared random state on disk. */
  19. static const char default_fname[] = "sr-state";
  20. /* Our shared random protocol state. There is only one possible state per
  21. * protocol run so this is the global state which is reset at every run once
  22. * the shared random value has been computed. */
  23. static sr_state_t *sr_state = NULL;
  24. /* Representation of our persistent state on disk. The sr_state above
  25. * contains the data parsed from this state. When we save to disk, we
  26. * translate the sr_state to this sr_disk_state. */
  27. static sr_disk_state_t *sr_disk_state = NULL;
  28. /* Disk state file keys. */
  29. static const char dstate_commit_key[] = "Commit";
  30. static const char dstate_prev_srv_key[] = "SharedRandPreviousValue";
  31. static const char dstate_cur_srv_key[] = "SharedRandCurrentValue";
  32. /* These next two are duplicates or near-duplicates from config.c */
  33. #define VAR(name, conftype, member, initvalue) \
  34. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(sr_disk_state_t, member), \
  35. initvalue }
  36. /* As VAR, but the option name and member name are the same. */
  37. #define V(member, conftype, initvalue) \
  38. VAR(#member, conftype, member, initvalue)
  39. /* Our persistent state magic number. */
  40. #define SR_DISK_STATE_MAGIC 0x98AB1254
  41. /* Each protocol phase has 12 rounds */
  42. #define SHARED_RANDOM_N_ROUNDS 12
  43. /* Number of phase we have in a protocol. */
  44. #define SHARED_RANDOM_N_PHASES 2
  45. static int
  46. disk_state_validate_cb(void *old_state, void *state, void *default_state,
  47. int from_setconf, char **msg);
  48. /* Array of variables that are saved to disk as a persistent state. */
  49. static config_var_t state_vars[] = {
  50. V(Version, INT, "0"),
  51. V(TorVersion, STRING, NULL),
  52. V(ValidAfter, ISOTIME, NULL),
  53. V(ValidUntil, ISOTIME, NULL),
  54. V(Commit, LINELIST, NULL),
  55. V(SharedRandValues, LINELIST_V, NULL),
  56. VAR("SharedRandPreviousValue",LINELIST_S, SharedRandValues, NULL),
  57. VAR("SharedRandCurrentValue", LINELIST_S, SharedRandValues, NULL),
  58. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  59. };
  60. /* "Extra" variable in the state that receives lines we can't parse. This
  61. * lets us preserve options from versions of Tor newer than us. */
  62. static config_var_t state_extra_var = {
  63. "__extra", CONFIG_TYPE_LINELIST,
  64. STRUCT_OFFSET(sr_disk_state_t, ExtraLines), NULL
  65. };
  66. /* Configuration format of sr_disk_state_t. */
  67. static const config_format_t state_format = {
  68. sizeof(sr_disk_state_t),
  69. SR_DISK_STATE_MAGIC,
  70. STRUCT_OFFSET(sr_disk_state_t, magic_),
  71. NULL,
  72. state_vars,
  73. disk_state_validate_cb,
  74. &state_extra_var,
  75. };
  76. /* Return the voting interval of the tor vote subsystem. */
  77. static int
  78. get_voting_interval(void)
  79. {
  80. int interval;
  81. networkstatus_t *consensus = networkstatus_get_live_consensus(time(NULL));
  82. if (consensus) {
  83. interval = (int)(consensus->fresh_until - consensus->valid_after);
  84. } else {
  85. /* Same for both a testing and real network. We voluntarily ignore the
  86. * InitialVotingInterval since it complexifies things and it doesn't
  87. * affect the SR protocol. */
  88. interval = get_options()->V3AuthVotingInterval;
  89. }
  90. tor_assert(interval > 0);
  91. return interval;
  92. }
  93. /* Given the time <b>now</b>, return the start time of the current round of
  94. * the SR protocol. For example, if it's 23:47:08, the current round thus
  95. * started at 23:47:00 for a voting interval of 10 seconds. */
  96. static time_t
  97. get_start_time_of_current_round(time_t now)
  98. {
  99. const or_options_t *options = get_options();
  100. int voting_interval = get_voting_interval();
  101. voting_schedule_t *new_voting_schedule =
  102. get_voting_schedule(options, now, LOG_INFO);
  103. tor_assert(new_voting_schedule);
  104. /* First, get the start time of the next round */
  105. time_t next_start = new_voting_schedule->interval_starts;
  106. /* Now roll back next_start by a voting interval to find the start time of
  107. the current round. */
  108. time_t curr_start = dirvote_get_start_of_next_interval(
  109. next_start - voting_interval - 1,
  110. voting_interval,
  111. options->TestingV3AuthVotingStartOffset);
  112. tor_free(new_voting_schedule);
  113. return curr_start;
  114. }
  115. /* Return the time we should expire the state file created at <b>now</b>.
  116. * We expire the state file in the beginning of the next protocol run. */
  117. STATIC time_t
  118. get_state_valid_until_time(time_t now)
  119. {
  120. int total_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  121. int current_round, voting_interval, rounds_left;
  122. time_t valid_until, beginning_of_current_round;
  123. voting_interval = get_voting_interval();
  124. /* Find the time the current round started. */
  125. beginning_of_current_round = get_start_time_of_current_round(now);
  126. /* Find how many rounds are left till the end of the protocol run */
  127. current_round = (now / voting_interval) % total_rounds;
  128. rounds_left = total_rounds - current_round;
  129. /* To find the valid-until time now, take the start time of the current
  130. * round and add to it the time it takes for the leftover rounds to
  131. * complete. */
  132. valid_until = beginning_of_current_round + (rounds_left * voting_interval);
  133. { /* Logging */
  134. char tbuf[ISO_TIME_LEN + 1];
  135. format_iso_time(tbuf, valid_until);
  136. log_debug(LD_DIR, "SR: Valid until time for state set to %s.", tbuf);
  137. }
  138. return valid_until;
  139. }
  140. /* Given the consensus 'valid-after' time, return the protocol phase we should
  141. * be in. */
  142. STATIC sr_phase_t
  143. get_sr_protocol_phase(time_t valid_after)
  144. {
  145. /* Shared random protocol has two phases, commit and reveal. */
  146. int total_periods = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  147. int current_slot;
  148. /* Split time into slots of size 'voting_interval'. See which slot we are
  149. * currently into, and find which phase it corresponds to. */
  150. current_slot = (valid_after / get_voting_interval()) % total_periods;
  151. if (current_slot < SHARED_RANDOM_N_ROUNDS) {
  152. return SR_PHASE_COMMIT;
  153. } else {
  154. return SR_PHASE_REVEAL;
  155. }
  156. }
  157. /* Add the given <b>commit</b> to <b>state</b>. It MUST be a valid commit
  158. * and there shouldn't be a commit from the same authority in the state
  159. * already else verification hasn't been done prior. This takes ownership of
  160. * the commit once in our state. */
  161. static void
  162. commit_add_to_state(sr_commit_t *commit, sr_state_t *state)
  163. {
  164. sr_commit_t *saved_commit;
  165. tor_assert(commit);
  166. tor_assert(state);
  167. saved_commit = digestmap_set(state->commits, commit->rsa_identity_fpr,
  168. commit);
  169. if (saved_commit != NULL) {
  170. /* This means we already have that commit in our state so adding twice
  171. * the same commit is either a code flow error, a corrupted disk state
  172. * or some new unknown issue. */
  173. log_warn(LD_DIR, "SR: Commit from %s exists in our state while "
  174. "adding it: '%s'", commit->rsa_identity_fpr,
  175. commit->encoded_commit);
  176. sr_commit_free(saved_commit);
  177. }
  178. }
  179. /* Helper: deallocate a commit object. (Used with digestmap_free(), which
  180. * requires a function pointer whose argument is void *). */
  181. static void
  182. commit_free_(void *p)
  183. {
  184. sr_commit_free(p);
  185. }
  186. /* Free a state that was allocated with state_new(). */
  187. static void
  188. state_free(sr_state_t *state)
  189. {
  190. if (state == NULL) {
  191. return;
  192. }
  193. tor_free(state->fname);
  194. digestmap_free(state->commits, commit_free_);
  195. tor_free(state->current_srv);
  196. tor_free(state->previous_srv);
  197. tor_free(state);
  198. }
  199. /* Allocate an sr_state_t object and returns it. If no <b>fname</b>, the
  200. * default file name is used. This function does NOT initialize the state
  201. * timestamp, phase or shared random value. NULL is never returned. */
  202. static sr_state_t *
  203. state_new(const char *fname, time_t now)
  204. {
  205. sr_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
  206. /* If file name is not provided, use default. */
  207. if (fname == NULL) {
  208. fname = default_fname;
  209. }
  210. new_state->fname = tor_strdup(fname);
  211. new_state->version = SR_PROTO_VERSION;
  212. new_state->commits = digestmap_new();
  213. new_state->phase = get_sr_protocol_phase(now);
  214. new_state->valid_until = get_state_valid_until_time(now);
  215. return new_state;
  216. }
  217. /* Set our global state pointer with the one given. */
  218. static void
  219. state_set(sr_state_t *state)
  220. {
  221. tor_assert(state);
  222. if (sr_state != NULL) {
  223. state_free(sr_state);
  224. }
  225. sr_state = state;
  226. }
  227. /* Free an allocated disk state. */
  228. static void
  229. disk_state_free(sr_disk_state_t *state)
  230. {
  231. if (state == NULL) {
  232. return;
  233. }
  234. config_free(&state_format, state);
  235. }
  236. /* Allocate a new disk state, initialize it and return it. */
  237. static sr_disk_state_t *
  238. disk_state_new(time_t now)
  239. {
  240. sr_disk_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
  241. new_state->magic_ = SR_DISK_STATE_MAGIC;
  242. new_state->Version = SR_PROTO_VERSION;
  243. new_state->TorVersion = tor_strdup(get_version());
  244. new_state->ValidUntil = get_state_valid_until_time(now);
  245. new_state->ValidAfter = now;
  246. /* Init config format. */
  247. config_init(&state_format, new_state);
  248. return new_state;
  249. }
  250. /* Set our global disk state with the given state. */
  251. static void
  252. disk_state_set(sr_disk_state_t *state)
  253. {
  254. tor_assert(state);
  255. if (sr_disk_state != NULL) {
  256. disk_state_free(sr_disk_state);
  257. }
  258. sr_disk_state = state;
  259. }
  260. /* Return -1 if the disk state is invalid (something in there that we can't or
  261. * shouldn't use). Return 0 if everything checks out. */
  262. static int
  263. disk_state_validate(const sr_disk_state_t *state)
  264. {
  265. time_t now;
  266. tor_assert(state);
  267. /* Do we support the protocol version in the state or is it 0 meaning
  268. * Version wasn't found in the state file or bad anyway ? */
  269. if (state->Version == 0 || state->Version > SR_PROTO_VERSION) {
  270. goto invalid;
  271. }
  272. /* If the valid until time is before now, we shouldn't use that state. */
  273. now = time(NULL);
  274. if (state->ValidUntil < now) {
  275. log_info(LD_DIR, "SR: Disk state has expired. Ignoring it.");
  276. goto invalid;
  277. }
  278. /* Make sure we don't have a valid after time that is earlier than a valid
  279. * until time which would make things not work well. */
  280. if (state->ValidAfter >= state->ValidUntil) {
  281. log_info(LD_DIR, "SR: Disk state valid after/until times are invalid.");
  282. goto invalid;
  283. }
  284. return 0;
  285. invalid:
  286. return -1;
  287. }
  288. /* Validate the disk state (NOP for now). */
  289. static int
  290. disk_state_validate_cb(void *old_state, void *state, void *default_state,
  291. int from_setconf, char **msg)
  292. {
  293. /* We don't use these; only options do. */
  294. (void) from_setconf;
  295. (void) default_state;
  296. (void) old_state;
  297. /* This is called by config_dump which is just before we are about to
  298. * write it to disk. At that point, our global memory state has been
  299. * copied to the disk state so it's fair to assume it's trustable. */
  300. (void) state;
  301. (void) msg;
  302. return 0;
  303. }
  304. /* Parse the Commit line(s) in the disk state and translate them to the
  305. * the memory state. Return 0 on success else -1 on error. */
  306. static int
  307. disk_state_parse_commits(sr_state_t *state,
  308. const sr_disk_state_t *disk_state)
  309. {
  310. config_line_t *line;
  311. smartlist_t *args = NULL;
  312. tor_assert(state);
  313. tor_assert(disk_state);
  314. for (line = disk_state->Commit; line; line = line->next) {
  315. sr_commit_t *commit = NULL;
  316. /* Extra safety. */
  317. if (strcasecmp(line->key, dstate_commit_key) ||
  318. line->value == NULL) {
  319. /* Ignore any lines that are not commits. */
  320. tor_fragile_assert();
  321. continue;
  322. }
  323. args = smartlist_new();
  324. smartlist_split_string(args, line->value, " ",
  325. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  326. if (smartlist_len(args) < 3) {
  327. log_warn(LD_BUG, "SR: Too few arguments in Commit Line: %s",
  328. escaped(line->value));
  329. goto error;
  330. }
  331. commit = sr_parse_commit(args);
  332. if (commit == NULL) {
  333. /* Ignore badly formed commit. It could also be a authority
  334. * fingerprint that we don't know about so it shouldn't be used. */
  335. continue;
  336. }
  337. /* Add commit to our state pointer. */
  338. commit_add_to_state(commit, state);
  339. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  340. smartlist_free(args);
  341. }
  342. return 0;
  343. error:
  344. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  345. smartlist_free(args);
  346. return -1;
  347. }
  348. /* Parse a share random value line from the disk state and save it to dst
  349. * which is an allocated srv object. Return 0 on success else -1. */
  350. static int
  351. disk_state_parse_srv(const char *value, sr_srv_t *dst)
  352. {
  353. int ret = -1;
  354. smartlist_t *args;
  355. sr_srv_t *srv;
  356. tor_assert(value);
  357. tor_assert(dst);
  358. args = smartlist_new();
  359. smartlist_split_string(args, value, " ",
  360. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  361. if (smartlist_len(args) < 2) {
  362. log_warn(LD_BUG, "SR: Too few arguments in shared random value. "
  363. "Line: %s", escaped(value));
  364. goto error;
  365. }
  366. srv = sr_parse_srv(args);
  367. if (srv == NULL) {
  368. goto error;
  369. }
  370. dst->num_reveals = srv->num_reveals;
  371. memcpy(dst->value, srv->value, sizeof(dst->value));
  372. tor_free(srv);
  373. ret = 0;
  374. error:
  375. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  376. smartlist_free(args);
  377. return ret;
  378. }
  379. /* Parse both SharedRandCurrentValue and SharedRandPreviousValue line from
  380. * the state. Return 0 on success else -1. */
  381. static int
  382. disk_state_parse_sr_values(sr_state_t *state,
  383. const sr_disk_state_t *disk_state)
  384. {
  385. /* Only one value per type (current or previous) is allowed so we keep
  386. * track of it with these flag. */
  387. unsigned int seen_previous = 0, seen_current = 0;
  388. config_line_t *line;
  389. sr_srv_t *srv = NULL;
  390. tor_assert(state);
  391. tor_assert(disk_state);
  392. for (line = disk_state->SharedRandValues; line; line = line->next) {
  393. if (line->value == NULL) {
  394. continue;
  395. }
  396. srv = tor_malloc_zero(sizeof(*srv));
  397. if (disk_state_parse_srv(line->value, srv) < 0) {
  398. log_warn(LD_BUG, "SR: Broken current SRV line in state %s",
  399. escaped(line->value));
  400. goto bad;
  401. }
  402. if (!strcasecmp(line->key, dstate_prev_srv_key)) {
  403. if (seen_previous) {
  404. log_warn(LD_DIR, "SR: Second previous SRV value seen. Bad state");
  405. goto bad;
  406. }
  407. state->previous_srv = srv;
  408. seen_previous = 1;
  409. } else if (!strcasecmp(line->key, dstate_cur_srv_key)) {
  410. if (seen_current) {
  411. log_warn(LD_DIR, "SR: Second current SRV value seen. Bad state");
  412. goto bad;
  413. }
  414. state->current_srv = srv;
  415. seen_current = 1;
  416. } else {
  417. /* Unknown key. Ignoring. */
  418. tor_free(srv);
  419. }
  420. }
  421. return 0;
  422. bad:
  423. tor_free(srv);
  424. return -1;
  425. }
  426. /* Parse the given disk state and set a newly allocated state. On success,
  427. * return that state else NULL. */
  428. static sr_state_t *
  429. disk_state_parse(const sr_disk_state_t *new_disk_state)
  430. {
  431. sr_state_t *new_state = state_new(default_fname, time(NULL));
  432. tor_assert(new_disk_state);
  433. new_state->version = new_disk_state->Version;
  434. new_state->valid_until = new_disk_state->ValidUntil;
  435. new_state->valid_after = new_disk_state->ValidAfter;
  436. /* Set our current phase according to the valid-after time in our disk
  437. * state. The disk state we are parsing contains everything for the phase
  438. * starting at valid_after so make sure our phase reflects that. */
  439. new_state->phase = get_sr_protocol_phase(new_state->valid_after);
  440. /* Parse the shared random values. */
  441. if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
  442. goto error;
  443. }
  444. /* Parse the commits. */
  445. if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
  446. goto error;
  447. }
  448. /* Great! This new state contains everything we had on disk. */
  449. return new_state;
  450. error:
  451. state_free(new_state);
  452. return NULL;
  453. }
  454. /* From a valid commit object and an allocated config line, set the line's
  455. * value to the state string representation of a commit. */
  456. static void
  457. disk_state_put_commit_line(const sr_commit_t *commit, config_line_t *line)
  458. {
  459. char *reveal_str = NULL;
  460. tor_assert(commit);
  461. tor_assert(line);
  462. if (!tor_mem_is_zero(commit->encoded_reveal,
  463. sizeof(commit->encoded_reveal))) {
  464. /* Add extra whitespace so we can format the line correctly. */
  465. tor_asprintf(&reveal_str, " %s", commit->encoded_reveal);
  466. }
  467. tor_asprintf(&line->value, "%s %s %s%s",
  468. crypto_digest_algorithm_get_name(commit->alg),
  469. commit->rsa_identity_fpr,
  470. commit->encoded_commit,
  471. reveal_str != NULL ? reveal_str : "");
  472. if (reveal_str != NULL) {
  473. memwipe(reveal_str, 0, strlen(reveal_str));
  474. tor_free(reveal_str);
  475. }
  476. }
  477. /* From a valid srv object and an allocated config line, set the line's
  478. * value to the state string representation of a shared random value. */
  479. static void
  480. disk_state_put_srv_line(const sr_srv_t *srv, config_line_t *line)
  481. {
  482. char encoded[HEX_DIGEST256_LEN + 1];
  483. tor_assert(line);
  484. /* No SRV value thus don't add the line. This is possible since we might
  485. * not have a current or previous SRV value in our state. */
  486. if (srv == NULL) {
  487. return;
  488. }
  489. base16_encode(encoded, sizeof(encoded), (const char *) srv->value,
  490. sizeof(srv->value));
  491. tor_asprintf(&line->value, "%d %s", srv->num_reveals, encoded);
  492. }
  493. /* Reset disk state that is free allocated memory and zeroed the object. */
  494. static void
  495. disk_state_reset(void)
  496. {
  497. config_free_lines(sr_disk_state->Commit);
  498. config_free_lines(sr_disk_state->SharedRandValues);
  499. config_free_lines(sr_disk_state->ExtraLines);
  500. memset(sr_disk_state, 0, sizeof(*sr_disk_state));
  501. sr_disk_state->magic_ = SR_DISK_STATE_MAGIC;
  502. sr_disk_state->TorVersion = tor_strdup(get_version());
  503. }
  504. /* Update our disk state based on our global SR state. */
  505. static void
  506. disk_state_update(void)
  507. {
  508. config_line_t **next, *line;
  509. tor_assert(sr_disk_state);
  510. tor_assert(sr_state);
  511. /* Reset current disk state. */
  512. disk_state_reset();
  513. /* First, update elements that we don't need to iterate over a list to
  514. * construct something. */
  515. sr_disk_state->Version = sr_state->version;
  516. sr_disk_state->ValidUntil = sr_state->valid_until;
  517. sr_disk_state->ValidAfter = sr_state->valid_after;
  518. /* Shared random values. */
  519. next = &sr_disk_state->SharedRandValues;
  520. *next = NULL;
  521. if (sr_state->previous_srv != NULL) {
  522. *next = line = tor_malloc_zero(sizeof(config_line_t));
  523. line->key = tor_strdup(dstate_prev_srv_key);
  524. disk_state_put_srv_line(sr_state->previous_srv, line);
  525. next = &(line->next);
  526. }
  527. if (sr_state->current_srv != NULL) {
  528. *next = line = tor_malloc_zero(sizeof(*line));
  529. line->key = tor_strdup(dstate_cur_srv_key);
  530. disk_state_put_srv_line(sr_state->current_srv, line);
  531. next = &(line->next);
  532. }
  533. /* Parse the commits and construct config line(s). */
  534. next = &sr_disk_state->Commit;
  535. DIGESTMAP_FOREACH(sr_state->commits, key, sr_commit_t *, commit) {
  536. *next = line = tor_malloc_zero(sizeof(*line));
  537. line->key = tor_strdup(dstate_commit_key);
  538. disk_state_put_commit_line(commit, line);
  539. next = &(line->next);
  540. } DIGESTMAP_FOREACH_END;
  541. }
  542. /* Load state from disk and put it into our disk state. If the state passes
  543. * validation, our global state will be updated with it. Return 0 on
  544. * success. On error, -EINVAL is returned if the state on disk did contained
  545. * something malformed or is unreadable. -ENOENT is returned indicating that
  546. * the state file is either empty of non existing. */
  547. static int
  548. disk_state_load_from_disk(void)
  549. {
  550. int ret;
  551. char *fname;
  552. fname = get_datadir_fname(default_fname);
  553. ret = disk_state_load_from_disk_impl(fname);
  554. tor_free(fname);
  555. return ret;
  556. }
  557. /* Helper for disk_state_load_from_disk(). */
  558. STATIC int
  559. disk_state_load_from_disk_impl(const char *fname)
  560. {
  561. int ret;
  562. char *content = NULL;
  563. sr_state_t *parsed_state = NULL;
  564. sr_disk_state_t *disk_state = NULL;
  565. /* Read content of file so we can parse it. */
  566. if ((content = read_file_to_str(fname, 0, NULL)) == NULL) {
  567. log_warn(LD_FS, "SR: Unable to read SR state file %s",
  568. escaped(fname));
  569. ret = -errno;
  570. goto error;
  571. }
  572. {
  573. config_line_t *lines = NULL;
  574. char *errmsg = NULL;
  575. /* Every error in this code path will return EINVAL. */
  576. ret = -EINVAL;
  577. if (config_get_lines(content, &lines, 0) < 0) {
  578. config_free_lines(lines);
  579. goto error;
  580. }
  581. disk_state = disk_state_new(time(NULL));
  582. config_assign(&state_format, disk_state, lines, 0, 0, &errmsg);
  583. config_free_lines(lines);
  584. if (errmsg) {
  585. log_warn(LD_DIR, "SR: Reading state error: %s", errmsg);
  586. tor_free(errmsg);
  587. goto error;
  588. }
  589. }
  590. /* So far so good, we've loaded our state file into our disk state. Let's
  591. * validate it and then parse it. */
  592. if (disk_state_validate(disk_state) < 0) {
  593. ret = -EINVAL;
  594. goto error;
  595. }
  596. parsed_state = disk_state_parse(disk_state);
  597. if (parsed_state == NULL) {
  598. ret = -EINVAL;
  599. goto error;
  600. }
  601. state_set(parsed_state);
  602. disk_state_set(disk_state);
  603. tor_free(content);
  604. log_notice(LD_DIR, "SR: State loaded successfully from file %s", fname);
  605. return 0;
  606. error:
  607. disk_state_free(disk_state);
  608. tor_free(content);
  609. return ret;
  610. }
  611. /* Save the disk state to disk but before that update it from the current
  612. * state so we always have the latest. Return 0 on success else -1. */
  613. static int
  614. disk_state_save_to_disk(void)
  615. {
  616. int ret;
  617. char *state, *content = NULL, *fname = NULL;
  618. char tbuf[ISO_TIME_LEN + 1];
  619. time_t now = time(NULL);
  620. /* If we didn't have the opportunity to setup an internal disk state,
  621. * don't bother saving something to disk. */
  622. if (sr_disk_state == NULL) {
  623. ret = 0;
  624. goto done;
  625. }
  626. /* Make sure that our disk state is up to date with our memory state
  627. * before saving it to disk. */
  628. disk_state_update();
  629. state = config_dump(&state_format, NULL, sr_disk_state, 0, 0);
  630. format_local_iso_time(tbuf, now);
  631. tor_asprintf(&content,
  632. "# Tor shared random state file last generated on %s "
  633. "local time\n"
  634. "# Other times below are in UTC\n"
  635. "# Please *do not* edit this file.\n\n%s",
  636. tbuf, state);
  637. tor_free(state);
  638. fname = get_datadir_fname(default_fname);
  639. if (write_str_to_file(fname, content, 0) < 0) {
  640. log_warn(LD_FS, "SR: Unable to write SR state to file %s", fname);
  641. ret = -1;
  642. goto done;
  643. }
  644. ret = 0;
  645. log_debug(LD_DIR, "SR: Saved state to file %s", fname);
  646. done:
  647. tor_free(fname);
  648. tor_free(content);
  649. return ret;
  650. }
  651. /* Helper function: return a commit using the RSA fingerprint of the
  652. * authority or NULL if no such commit is known. */
  653. static sr_commit_t *
  654. state_query_get_commit(const char *rsa_fpr)
  655. {
  656. tor_assert(rsa_fpr);
  657. return digestmap_get(sr_state->commits, rsa_fpr);
  658. }
  659. /* Helper function: This handles the GET state action using an
  660. * <b>obj_type</b> and <b>data</b> needed for the action. */
  661. static void *
  662. state_query_get_(sr_state_object_t obj_type, const void *data)
  663. {
  664. void *obj = NULL;
  665. switch (obj_type) {
  666. case SR_STATE_OBJ_COMMIT:
  667. {
  668. obj = state_query_get_commit(data);
  669. break;
  670. }
  671. case SR_STATE_OBJ_COMMITS:
  672. obj = sr_state->commits;
  673. break;
  674. case SR_STATE_OBJ_CURSRV:
  675. obj = sr_state->current_srv;
  676. break;
  677. case SR_STATE_OBJ_PREVSRV:
  678. obj = sr_state->previous_srv;
  679. break;
  680. case SR_STATE_OBJ_PHASE:
  681. obj = &sr_state->phase;
  682. break;
  683. case SR_STATE_OBJ_VALID_AFTER:
  684. default:
  685. tor_assert(0);
  686. }
  687. return obj;
  688. }
  689. /* Helper function: This handles the PUT state action using an
  690. * <b>obj_type</b> and <b>data</b> needed for the action. */
  691. static void
  692. state_query_put_(sr_state_object_t obj_type, void *data)
  693. {
  694. switch (obj_type) {
  695. case SR_STATE_OBJ_COMMIT:
  696. {
  697. sr_commit_t *commit = data;
  698. tor_assert(commit);
  699. commit_add_to_state(commit, sr_state);
  700. break;
  701. }
  702. case SR_STATE_OBJ_CURSRV:
  703. sr_state->current_srv = (sr_srv_t *) data;
  704. break;
  705. case SR_STATE_OBJ_PREVSRV:
  706. sr_state->previous_srv = (sr_srv_t *) data;
  707. break;
  708. case SR_STATE_OBJ_VALID_AFTER:
  709. sr_state->valid_after = *((time_t *) data);
  710. break;
  711. /* It's not allowed to change the phase nor the full commitments map from
  712. * the state. The phase is decided during a strict process post voting and
  713. * the commits should be put individually. */
  714. case SR_STATE_OBJ_PHASE:
  715. case SR_STATE_OBJ_COMMITS:
  716. default:
  717. tor_assert(0);
  718. }
  719. }
  720. /* Helper function: This handles the DEL state action using an
  721. * <b>obj_type</b> and <b>data</b> needed for the action. */
  722. static void
  723. state_query_del_all_(sr_state_object_t obj_type)
  724. {
  725. switch (obj_type) {
  726. case SR_STATE_OBJ_COMMIT:
  727. {
  728. /* We are in a new protocol run so cleanup commitments. */
  729. DIGESTMAP_FOREACH_MODIFY(sr_state->commits, key, sr_commit_t *, c) {
  730. sr_commit_free(c);
  731. MAP_DEL_CURRENT(key);
  732. } DIGESTMAP_FOREACH_END;
  733. break;
  734. }
  735. /* The following object are _NOT_ suppose to be removed. */
  736. case SR_STATE_OBJ_CURSRV:
  737. case SR_STATE_OBJ_PREVSRV:
  738. case SR_STATE_OBJ_PHASE:
  739. case SR_STATE_OBJ_COMMITS:
  740. case SR_STATE_OBJ_VALID_AFTER:
  741. default:
  742. tor_assert(0);
  743. }
  744. }
  745. /* Query state using an <b>action</b> for an object type <b>obj_type</b>.
  746. * The <b>data</b> pointer needs to point to an object that the action needs
  747. * to use and if anything is required to be returned, it is stored in
  748. * <b>out</b>.
  749. *
  750. * This mechanism exists so we have one single point where we synchronized
  751. * our memory state with our disk state for every actions that changes it.
  752. * We then trigger a write on disk immediately.
  753. *
  754. * This should be the only entry point to our memory state. It's used by all
  755. * our state accessors and should be in the future. */
  756. static void
  757. state_query(sr_state_action_t action, sr_state_object_t obj_type,
  758. void *data, void **out)
  759. {
  760. switch (action) {
  761. case SR_STATE_ACTION_GET:
  762. *out = state_query_get_(obj_type, data);
  763. break;
  764. case SR_STATE_ACTION_PUT:
  765. state_query_put_(obj_type, data);
  766. break;
  767. case SR_STATE_ACTION_DEL_ALL:
  768. state_query_del_all_(obj_type);
  769. break;
  770. case SR_STATE_ACTION_SAVE:
  771. /* Only trigger a disk state save. */
  772. break;
  773. default:
  774. tor_assert(0);
  775. }
  776. /* If the action actually changes the state, immediately save it to disk.
  777. * The following will sync the state -> disk state and then save it. */
  778. if (action != SR_STATE_ACTION_GET) {
  779. disk_state_save_to_disk();
  780. }
  781. }
  782. /* Set valid after time in the our state. */
  783. void
  784. sr_state_set_valid_after(time_t valid_after)
  785. {
  786. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_VALID_AFTER,
  787. (void *) &valid_after, NULL);
  788. }
  789. /* Return the phase we are currently in according to our state. */
  790. sr_phase_t
  791. sr_state_get_phase(void)
  792. {
  793. void *ptr;
  794. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PHASE, NULL, &ptr);
  795. return *(sr_phase_t *) ptr;
  796. }
  797. /* Return the previous SRV value from our state. Value CAN be NULL. */
  798. sr_srv_t *
  799. sr_state_get_previous_srv(void)
  800. {
  801. sr_srv_t *srv;
  802. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PREVSRV, NULL,
  803. (void *) &srv);
  804. return srv;
  805. }
  806. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  807. * object ownership is transfered to the state object. */
  808. void
  809. sr_state_set_previous_srv(const sr_srv_t *srv)
  810. {
  811. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_PREVSRV, (void *) srv,
  812. NULL);
  813. }
  814. /* Return the current SRV value from our state. Value CAN be NULL. */
  815. sr_srv_t *
  816. sr_state_get_current_srv(void)
  817. {
  818. sr_srv_t *srv;
  819. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_CURSRV, NULL,
  820. (void *) &srv);
  821. return srv;
  822. }
  823. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  824. * object ownership is transfered to the state object. */
  825. void
  826. sr_state_set_current_srv(const sr_srv_t *srv)
  827. {
  828. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_CURSRV, (void *) srv,
  829. NULL);
  830. }
  831. /* Return a pointer to the commits map from our state. CANNOT be NULL. */
  832. digestmap_t *
  833. sr_state_get_commits(void)
  834. {
  835. digestmap_t *commits;
  836. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMITS,
  837. NULL, (void *) &commits);
  838. tor_assert(commits);
  839. return commits;
  840. }
  841. /* Return commit object from the given authority digest <b>identity</b>.
  842. * Return NULL if not found. */
  843. sr_commit_t *
  844. sr_state_get_commit(const char *rsa_fpr)
  845. {
  846. sr_commit_t *commit;
  847. tor_assert(rsa_fpr);
  848. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMIT,
  849. (void *) rsa_fpr, (void *) &commit);
  850. return commit;
  851. }
  852. /* Add <b>commit</b> to the permanent state. The commit object ownership is
  853. * transfered to the state so the caller MUST not free it. */
  854. void
  855. sr_state_add_commit(sr_commit_t *commit)
  856. {
  857. tor_assert(commit);
  858. /* Put the commit to the global state. */
  859. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_COMMIT,
  860. (void *) commit, NULL);
  861. log_debug(LD_DIR, "SR: Commit from %s has been added to our state.",
  862. commit->rsa_identity_fpr);
  863. }
  864. /* Remove all commits from our state. */
  865. void
  866. sr_state_delete_commits(void)
  867. {
  868. state_query(SR_STATE_ACTION_DEL_ALL, SR_STATE_OBJ_COMMIT, NULL, NULL);
  869. }
  870. /* Set the fresh SRV flag from our state. This doesn't need to trigger a
  871. * disk state synchronization so we directly change the state. */
  872. void
  873. sr_state_set_fresh_srv(void)
  874. {
  875. sr_state->is_srv_fresh = 1;
  876. }
  877. /* Unset the fresh SRV flag from our state. This doesn't need to trigger a
  878. * disk state synchronization so we directly change the state. */
  879. void
  880. sr_state_unset_fresh_srv(void)
  881. {
  882. sr_state->is_srv_fresh = 0;
  883. }
  884. /* Return the value of the fresh SRV flag. */
  885. unsigned int
  886. sr_state_srv_is_fresh(void)
  887. {
  888. return sr_state->is_srv_fresh;
  889. }
  890. /* Cleanup and free our disk and memory state. */
  891. void
  892. sr_state_free(void)
  893. {
  894. state_free(sr_state);
  895. disk_state_free(sr_disk_state);
  896. /* Nullify our global state. */
  897. sr_state = NULL;
  898. sr_disk_state = NULL;
  899. }
  900. /* Save our current state in memory to disk. */
  901. void
  902. sr_state_save(void)
  903. {
  904. /* Query a SAVE action on our current state so it's synced and saved. */
  905. state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
  906. }
  907. /* Initialize the disk and memory state.
  908. *
  909. * If save_to_disk is set to 1, the state is immediately saved to disk after
  910. * creation else it's not thus only kept in memory.
  911. * If read_from_disk is set to 1, we try to load the state from the disk and
  912. * if not found, a new state is created.
  913. *
  914. * Return 0 on success else a negative value on error. */
  915. int
  916. sr_state_init(int save_to_disk, int read_from_disk)
  917. {
  918. int ret = -ENOENT;
  919. time_t now = time(NULL);
  920. /* We shouldn't have those assigned. */
  921. tor_assert(sr_disk_state == NULL);
  922. tor_assert(sr_state == NULL);
  923. /* First, try to load the state from disk. */
  924. if (read_from_disk) {
  925. ret = disk_state_load_from_disk();
  926. }
  927. if (ret < 0) {
  928. switch (-ret) {
  929. case EINVAL:
  930. /* We have a state on disk but it contains something we couldn't parse
  931. * or an invalid entry in the state file. Let's remove it since it's
  932. * obviously unusable and replace it by an new fresh state below. */
  933. case ENOENT:
  934. {
  935. /* No state on disk so allocate our states for the first time. */
  936. sr_state_t *new_state = state_new(default_fname, now);
  937. sr_disk_state_t *new_disk_state = disk_state_new(now);
  938. state_set(new_state);
  939. /* It's important to set our disk state pointer since the save call
  940. * below uses it to synchronized it with our memory state. */
  941. disk_state_set(new_disk_state);
  942. /* No entry, let's save our new state to disk. */
  943. if (save_to_disk && disk_state_save_to_disk() < 0) {
  944. goto error;
  945. }
  946. break;
  947. }
  948. default:
  949. /* Big problem. Not possible. */
  950. tor_assert(0);
  951. }
  952. }
  953. return 0;
  954. error:
  955. return -1;
  956. }