shared_random_state.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. /* Copyright (c) 2016-2017, 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. /* String representation of a protocol phase. */
  21. static const char *phase_str[] = { "unknown", "commit", "reveal" };
  22. /* Our shared random protocol state. There is only one possible state per
  23. * protocol run so this is the global state which is reset at every run once
  24. * the shared random value has been computed. */
  25. static sr_state_t *sr_state = NULL;
  26. /* Representation of our persistent state on disk. The sr_state above
  27. * contains the data parsed from this state. When we save to disk, we
  28. * translate the sr_state to this sr_disk_state. */
  29. static sr_disk_state_t *sr_disk_state = NULL;
  30. /* Disk state file keys. */
  31. static const char dstate_commit_key[] = "Commit";
  32. static const char dstate_prev_srv_key[] = "SharedRandPreviousValue";
  33. static const char dstate_cur_srv_key[] = "SharedRandCurrentValue";
  34. /* These next two are duplicates or near-duplicates from config.c */
  35. #define VAR(name, conftype, member, initvalue) \
  36. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(sr_disk_state_t, member), \
  37. initvalue }
  38. /* As VAR, but the option name and member name are the same. */
  39. #define V(member, conftype, initvalue) \
  40. VAR(#member, conftype, member, initvalue)
  41. /* Our persistent state magic number. */
  42. #define SR_DISK_STATE_MAGIC 0x98AB1254
  43. /* Each protocol phase has 12 rounds */
  44. #define SHARED_RANDOM_N_ROUNDS 12
  45. /* Number of phase we have in a protocol. */
  46. #define SHARED_RANDOM_N_PHASES 2
  47. static int
  48. disk_state_validate_cb(void *old_state, void *state, void *default_state,
  49. int from_setconf, char **msg);
  50. /* Array of variables that are saved to disk as a persistent state. */
  51. static config_var_t state_vars[] = {
  52. V(Version, UINT, "0"),
  53. V(TorVersion, STRING, NULL),
  54. V(ValidAfter, ISOTIME, NULL),
  55. V(ValidUntil, ISOTIME, NULL),
  56. V(Commit, LINELIST, NULL),
  57. V(SharedRandValues, LINELIST_V, NULL),
  58. VAR("SharedRandPreviousValue",LINELIST_S, SharedRandValues, NULL),
  59. VAR("SharedRandCurrentValue", LINELIST_S, SharedRandValues, NULL),
  60. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  61. };
  62. /* "Extra" variable in the state that receives lines we can't parse. This
  63. * lets us preserve options from versions of Tor newer than us. */
  64. static config_var_t state_extra_var = {
  65. "__extra", CONFIG_TYPE_LINELIST,
  66. STRUCT_OFFSET(sr_disk_state_t, ExtraLines), NULL
  67. };
  68. /* Configuration format of sr_disk_state_t. */
  69. static const config_format_t state_format = {
  70. sizeof(sr_disk_state_t),
  71. SR_DISK_STATE_MAGIC,
  72. STRUCT_OFFSET(sr_disk_state_t, magic_),
  73. NULL,
  74. NULL,
  75. state_vars,
  76. disk_state_validate_cb,
  77. &state_extra_var,
  78. };
  79. /* Return a string representation of a protocol phase. */
  80. STATIC const char *
  81. get_phase_str(sr_phase_t phase)
  82. {
  83. const char *the_string = NULL;
  84. switch (phase) {
  85. case SR_PHASE_COMMIT:
  86. case SR_PHASE_REVEAL:
  87. the_string = phase_str[phase];
  88. break;
  89. default:
  90. /* Unknown phase shouldn't be possible. */
  91. tor_assert(0);
  92. }
  93. return the_string;
  94. }
  95. /* Return the voting interval of the tor vote subsystem. */
  96. static int
  97. get_voting_interval(void)
  98. {
  99. int interval;
  100. networkstatus_t *consensus = networkstatus_get_live_consensus(time(NULL));
  101. if (consensus) {
  102. interval = (int)(consensus->fresh_until - consensus->valid_after);
  103. } else {
  104. /* Same for both a testing and real network. We voluntarily ignore the
  105. * InitialVotingInterval since it complexifies things and it doesn't
  106. * affect the SR protocol. */
  107. interval = get_options()->V3AuthVotingInterval;
  108. }
  109. tor_assert(interval > 0);
  110. return interval;
  111. }
  112. /* Given the time <b>now</b>, return the start time of the current round of
  113. * the SR protocol. For example, if it's 23:47:08, the current round thus
  114. * started at 23:47:00 for a voting interval of 10 seconds. */
  115. static time_t
  116. get_start_time_of_current_round(time_t now)
  117. {
  118. const or_options_t *options = get_options();
  119. int voting_interval = get_voting_interval();
  120. voting_schedule_t *new_voting_schedule =
  121. get_voting_schedule(options, now, LOG_INFO);
  122. tor_assert(new_voting_schedule);
  123. /* First, get the start time of the next round */
  124. time_t next_start = new_voting_schedule->interval_starts;
  125. /* Now roll back next_start by a voting interval to find the start time of
  126. the current round. */
  127. time_t curr_start = dirvote_get_start_of_next_interval(
  128. next_start - voting_interval - 1,
  129. voting_interval,
  130. options->TestingV3AuthVotingStartOffset);
  131. voting_schedule_free(new_voting_schedule);
  132. return curr_start;
  133. }
  134. /** Return the start time of the current SR protocol run. For example, if the
  135. * time is 23/06/2017 23:47:08 and a full SR protocol run is 24 hours, this
  136. * function should return 23/06/2017 00:00:00. */
  137. time_t
  138. sr_state_get_start_time_of_current_protocol_run(time_t now)
  139. {
  140. int total_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  141. int voting_interval = get_voting_interval();
  142. /* Find the time the current round started. */
  143. time_t beginning_of_current_round = get_start_time_of_current_round(now);
  144. /* Get current SR protocol round */
  145. int current_round = (now / voting_interval) % total_rounds;
  146. /* Get start time by subtracting the time elapsed from the beginning of the
  147. protocol run */
  148. time_t time_elapsed_since_start_of_run = current_round * voting_interval;
  149. return beginning_of_current_round - time_elapsed_since_start_of_run;
  150. }
  151. /** Return the time (in seconds) it takes to complete a full SR protocol phase
  152. * (e.g. the commit phase). */
  153. unsigned int
  154. sr_state_get_phase_duration(void)
  155. {
  156. return SHARED_RANDOM_N_ROUNDS * get_voting_interval();
  157. }
  158. /** Return the time (in seconds) it takes to complete a full SR protocol run */
  159. unsigned int
  160. sr_state_get_protocol_run_duration(void)
  161. {
  162. int total_protocol_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  163. return total_protocol_rounds * get_voting_interval();
  164. }
  165. /* Return the time we should expire the state file created at <b>now</b>.
  166. * We expire the state file in the beginning of the next protocol run. */
  167. STATIC time_t
  168. get_state_valid_until_time(time_t now)
  169. {
  170. int total_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  171. int current_round, voting_interval, rounds_left;
  172. time_t valid_until, beginning_of_current_round;
  173. voting_interval = get_voting_interval();
  174. /* Find the time the current round started. */
  175. beginning_of_current_round = get_start_time_of_current_round(now);
  176. /* Find how many rounds are left till the end of the protocol run */
  177. current_round = (now / voting_interval) % total_rounds;
  178. rounds_left = total_rounds - current_round;
  179. /* To find the valid-until time now, take the start time of the current
  180. * round and add to it the time it takes for the leftover rounds to
  181. * complete. */
  182. valid_until = beginning_of_current_round + (rounds_left * voting_interval);
  183. { /* Logging */
  184. char tbuf[ISO_TIME_LEN + 1];
  185. format_iso_time(tbuf, valid_until);
  186. log_debug(LD_DIR, "SR: Valid until time for state set to %s.", tbuf);
  187. }
  188. return valid_until;
  189. }
  190. /* Given the consensus 'valid-after' time, return the protocol phase we should
  191. * be in. */
  192. STATIC sr_phase_t
  193. get_sr_protocol_phase(time_t valid_after)
  194. {
  195. /* Shared random protocol has two phases, commit and reveal. */
  196. int total_periods = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
  197. int current_slot;
  198. /* Split time into slots of size 'voting_interval'. See which slot we are
  199. * currently into, and find which phase it corresponds to. */
  200. current_slot = (valid_after / get_voting_interval()) % total_periods;
  201. if (current_slot < SHARED_RANDOM_N_ROUNDS) {
  202. return SR_PHASE_COMMIT;
  203. } else {
  204. return SR_PHASE_REVEAL;
  205. }
  206. }
  207. /* Add the given <b>commit</b> to <b>state</b>. It MUST be a valid commit
  208. * and there shouldn't be a commit from the same authority in the state
  209. * already else verification hasn't been done prior. This takes ownership of
  210. * the commit once in our state. */
  211. static void
  212. commit_add_to_state(sr_commit_t *commit, sr_state_t *state)
  213. {
  214. sr_commit_t *saved_commit;
  215. tor_assert(commit);
  216. tor_assert(state);
  217. saved_commit = digestmap_set(state->commits, commit->rsa_identity,
  218. commit);
  219. if (saved_commit != NULL) {
  220. /* This means we already have that commit in our state so adding twice
  221. * the same commit is either a code flow error, a corrupted disk state
  222. * or some new unknown issue. */
  223. log_warn(LD_DIR, "SR: Commit from %s exists in our state while "
  224. "adding it: '%s'", sr_commit_get_rsa_fpr(commit),
  225. commit->encoded_commit);
  226. sr_commit_free(saved_commit);
  227. }
  228. }
  229. /* Helper: deallocate a commit object. (Used with digestmap_free(), which
  230. * requires a function pointer whose argument is void *). */
  231. static void
  232. commit_free_(void *p)
  233. {
  234. sr_commit_free(p);
  235. }
  236. /* Free a state that was allocated with state_new(). */
  237. static void
  238. state_free(sr_state_t *state)
  239. {
  240. if (state == NULL) {
  241. return;
  242. }
  243. tor_free(state->fname);
  244. digestmap_free(state->commits, commit_free_);
  245. tor_free(state->current_srv);
  246. tor_free(state->previous_srv);
  247. tor_free(state);
  248. }
  249. /* Allocate an sr_state_t object and returns it. If no <b>fname</b>, the
  250. * default file name is used. This function does NOT initialize the state
  251. * timestamp, phase or shared random value. NULL is never returned. */
  252. static sr_state_t *
  253. state_new(const char *fname, time_t now)
  254. {
  255. sr_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
  256. /* If file name is not provided, use default. */
  257. if (fname == NULL) {
  258. fname = default_fname;
  259. }
  260. new_state->fname = tor_strdup(fname);
  261. new_state->version = SR_PROTO_VERSION;
  262. new_state->commits = digestmap_new();
  263. new_state->phase = get_sr_protocol_phase(now);
  264. new_state->valid_until = get_state_valid_until_time(now);
  265. return new_state;
  266. }
  267. /* Set our global state pointer with the one given. */
  268. static void
  269. state_set(sr_state_t *state)
  270. {
  271. tor_assert(state);
  272. if (sr_state != NULL) {
  273. state_free(sr_state);
  274. }
  275. sr_state = state;
  276. }
  277. /* Free an allocated disk state. */
  278. static void
  279. disk_state_free(sr_disk_state_t *state)
  280. {
  281. if (state == NULL) {
  282. return;
  283. }
  284. config_free(&state_format, state);
  285. }
  286. /* Allocate a new disk state, initialize it and return it. */
  287. static sr_disk_state_t *
  288. disk_state_new(time_t now)
  289. {
  290. sr_disk_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
  291. new_state->magic_ = SR_DISK_STATE_MAGIC;
  292. new_state->Version = SR_PROTO_VERSION;
  293. new_state->TorVersion = tor_strdup(get_version());
  294. new_state->ValidUntil = get_state_valid_until_time(now);
  295. new_state->ValidAfter = now;
  296. /* Init config format. */
  297. config_init(&state_format, new_state);
  298. return new_state;
  299. }
  300. /* Set our global disk state with the given state. */
  301. static void
  302. disk_state_set(sr_disk_state_t *state)
  303. {
  304. tor_assert(state);
  305. if (sr_disk_state != NULL) {
  306. disk_state_free(sr_disk_state);
  307. }
  308. sr_disk_state = state;
  309. }
  310. /* Return -1 if the disk state is invalid (something in there that we can't or
  311. * shouldn't use). Return 0 if everything checks out. */
  312. static int
  313. disk_state_validate(const sr_disk_state_t *state)
  314. {
  315. time_t now;
  316. tor_assert(state);
  317. /* Do we support the protocol version in the state or is it 0 meaning
  318. * Version wasn't found in the state file or bad anyway ? */
  319. if (state->Version == 0 || state->Version > SR_PROTO_VERSION) {
  320. goto invalid;
  321. }
  322. /* If the valid until time is before now, we shouldn't use that state. */
  323. now = time(NULL);
  324. if (state->ValidUntil < now) {
  325. log_info(LD_DIR, "SR: Disk state has expired. Ignoring it.");
  326. goto invalid;
  327. }
  328. /* Make sure we don't have a valid after time that is earlier than a valid
  329. * until time which would make things not work well. */
  330. if (state->ValidAfter >= state->ValidUntil) {
  331. log_info(LD_DIR, "SR: Disk state valid after/until times are invalid.");
  332. goto invalid;
  333. }
  334. return 0;
  335. invalid:
  336. return -1;
  337. }
  338. /* Validate the disk state (NOP for now). */
  339. static int
  340. disk_state_validate_cb(void *old_state, void *state, void *default_state,
  341. int from_setconf, char **msg)
  342. {
  343. /* We don't use these; only options do. */
  344. (void) from_setconf;
  345. (void) default_state;
  346. (void) old_state;
  347. /* This is called by config_dump which is just before we are about to
  348. * write it to disk. At that point, our global memory state has been
  349. * copied to the disk state so it's fair to assume it's trustable. */
  350. (void) state;
  351. (void) msg;
  352. return 0;
  353. }
  354. /* Parse the Commit line(s) in the disk state and translate them to the
  355. * the memory state. Return 0 on success else -1 on error. */
  356. static int
  357. disk_state_parse_commits(sr_state_t *state,
  358. const sr_disk_state_t *disk_state)
  359. {
  360. config_line_t *line;
  361. smartlist_t *args = NULL;
  362. tor_assert(state);
  363. tor_assert(disk_state);
  364. for (line = disk_state->Commit; line; line = line->next) {
  365. sr_commit_t *commit = NULL;
  366. /* Extra safety. */
  367. if (strcasecmp(line->key, dstate_commit_key) ||
  368. line->value == NULL) {
  369. /* Ignore any lines that are not commits. */
  370. tor_fragile_assert();
  371. continue;
  372. }
  373. args = smartlist_new();
  374. smartlist_split_string(args, line->value, " ",
  375. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  376. if (smartlist_len(args) < 3) {
  377. log_warn(LD_BUG, "SR: Too few arguments in Commit Line: %s",
  378. escaped(line->value));
  379. goto error;
  380. }
  381. commit = sr_parse_commit(args);
  382. if (commit == NULL) {
  383. /* Ignore badly formed commit. It could also be a authority
  384. * fingerprint that we don't know about so it shouldn't be used. */
  385. continue;
  386. }
  387. /* We consider parseable commit from our disk state to be valid because
  388. * they need to be in the first place to get in there. */
  389. commit->valid = 1;
  390. /* Add commit to our state pointer. */
  391. commit_add_to_state(commit, state);
  392. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  393. smartlist_free(args);
  394. }
  395. return 0;
  396. error:
  397. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  398. smartlist_free(args);
  399. return -1;
  400. }
  401. /* Parse a share random value line from the disk state and save it to dst
  402. * which is an allocated srv object. Return 0 on success else -1. */
  403. static int
  404. disk_state_parse_srv(const char *value, sr_srv_t *dst)
  405. {
  406. int ret = -1;
  407. smartlist_t *args;
  408. sr_srv_t *srv;
  409. tor_assert(value);
  410. tor_assert(dst);
  411. args = smartlist_new();
  412. smartlist_split_string(args, value, " ",
  413. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  414. if (smartlist_len(args) < 2) {
  415. log_warn(LD_BUG, "SR: Too few arguments in shared random value. "
  416. "Line: %s", escaped(value));
  417. goto error;
  418. }
  419. srv = sr_parse_srv(args);
  420. if (srv == NULL) {
  421. goto error;
  422. }
  423. dst->num_reveals = srv->num_reveals;
  424. memcpy(dst->value, srv->value, sizeof(dst->value));
  425. tor_free(srv);
  426. ret = 0;
  427. error:
  428. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  429. smartlist_free(args);
  430. return ret;
  431. }
  432. /* Parse both SharedRandCurrentValue and SharedRandPreviousValue line from
  433. * the state. Return 0 on success else -1. */
  434. static int
  435. disk_state_parse_sr_values(sr_state_t *state,
  436. const sr_disk_state_t *disk_state)
  437. {
  438. /* Only one value per type (current or previous) is allowed so we keep
  439. * track of it with these flag. */
  440. unsigned int seen_previous = 0, seen_current = 0;
  441. config_line_t *line;
  442. sr_srv_t *srv = NULL;
  443. tor_assert(state);
  444. tor_assert(disk_state);
  445. for (line = disk_state->SharedRandValues; line; line = line->next) {
  446. if (line->value == NULL) {
  447. continue;
  448. }
  449. srv = tor_malloc_zero(sizeof(*srv));
  450. if (disk_state_parse_srv(line->value, srv) < 0) {
  451. log_warn(LD_BUG, "SR: Broken current SRV line in state %s",
  452. escaped(line->value));
  453. goto bad;
  454. }
  455. if (!strcasecmp(line->key, dstate_prev_srv_key)) {
  456. if (seen_previous) {
  457. log_warn(LD_DIR, "SR: Second previous SRV value seen. Bad state");
  458. goto bad;
  459. }
  460. state->previous_srv = srv;
  461. seen_previous = 1;
  462. } else if (!strcasecmp(line->key, dstate_cur_srv_key)) {
  463. if (seen_current) {
  464. log_warn(LD_DIR, "SR: Second current SRV value seen. Bad state");
  465. goto bad;
  466. }
  467. state->current_srv = srv;
  468. seen_current = 1;
  469. } else {
  470. /* Unknown key. Ignoring. */
  471. tor_free(srv);
  472. }
  473. }
  474. return 0;
  475. bad:
  476. tor_free(srv);
  477. return -1;
  478. }
  479. /* Parse the given disk state and set a newly allocated state. On success,
  480. * return that state else NULL. */
  481. static sr_state_t *
  482. disk_state_parse(const sr_disk_state_t *new_disk_state)
  483. {
  484. sr_state_t *new_state = state_new(default_fname, time(NULL));
  485. tor_assert(new_disk_state);
  486. new_state->version = new_disk_state->Version;
  487. new_state->valid_until = new_disk_state->ValidUntil;
  488. new_state->valid_after = new_disk_state->ValidAfter;
  489. /* Set our current phase according to the valid-after time in our disk
  490. * state. The disk state we are parsing contains everything for the phase
  491. * starting at valid_after so make sure our phase reflects that. */
  492. new_state->phase = get_sr_protocol_phase(new_state->valid_after);
  493. /* Parse the shared random values. */
  494. if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
  495. goto error;
  496. }
  497. /* Parse the commits. */
  498. if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
  499. goto error;
  500. }
  501. /* Great! This new state contains everything we had on disk. */
  502. return new_state;
  503. error:
  504. state_free(new_state);
  505. return NULL;
  506. }
  507. /* From a valid commit object and an allocated config line, set the line's
  508. * value to the state string representation of a commit. */
  509. static void
  510. disk_state_put_commit_line(const sr_commit_t *commit, config_line_t *line)
  511. {
  512. char *reveal_str = NULL;
  513. tor_assert(commit);
  514. tor_assert(line);
  515. if (!tor_mem_is_zero(commit->encoded_reveal,
  516. sizeof(commit->encoded_reveal))) {
  517. /* Add extra whitespace so we can format the line correctly. */
  518. tor_asprintf(&reveal_str, " %s", commit->encoded_reveal);
  519. }
  520. tor_asprintf(&line->value, "%u %s %s %s%s",
  521. SR_PROTO_VERSION,
  522. crypto_digest_algorithm_get_name(commit->alg),
  523. sr_commit_get_rsa_fpr(commit),
  524. commit->encoded_commit,
  525. reveal_str != NULL ? reveal_str : "");
  526. if (reveal_str != NULL) {
  527. memwipe(reveal_str, 0, strlen(reveal_str));
  528. tor_free(reveal_str);
  529. }
  530. }
  531. /* From a valid srv object and an allocated config line, set the line's
  532. * value to the state string representation of a shared random value. */
  533. static void
  534. disk_state_put_srv_line(const sr_srv_t *srv, config_line_t *line)
  535. {
  536. char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  537. tor_assert(line);
  538. /* No SRV value thus don't add the line. This is possible since we might
  539. * not have a current or previous SRV value in our state. */
  540. if (srv == NULL) {
  541. return;
  542. }
  543. sr_srv_encode(encoded, sizeof(encoded), srv);
  544. tor_asprintf(&line->value, "%" PRIu64 " %s", srv->num_reveals, encoded);
  545. }
  546. /* Reset disk state that is free allocated memory and zeroed the object. */
  547. static void
  548. disk_state_reset(void)
  549. {
  550. /* Free allocated memory */
  551. config_free_lines(sr_disk_state->Commit);
  552. config_free_lines(sr_disk_state->SharedRandValues);
  553. config_free_lines(sr_disk_state->ExtraLines);
  554. tor_free(sr_disk_state->TorVersion);
  555. /* Clean up the struct */
  556. memset(sr_disk_state, 0, sizeof(*sr_disk_state));
  557. /* Reset it with useful data */
  558. sr_disk_state->magic_ = SR_DISK_STATE_MAGIC;
  559. sr_disk_state->TorVersion = tor_strdup(get_version());
  560. }
  561. /* Update our disk state based on our global SR state. */
  562. static void
  563. disk_state_update(void)
  564. {
  565. config_line_t **next, *line;
  566. tor_assert(sr_disk_state);
  567. tor_assert(sr_state);
  568. /* Reset current disk state. */
  569. disk_state_reset();
  570. /* First, update elements that we don't need to do a construction. */
  571. sr_disk_state->Version = sr_state->version;
  572. sr_disk_state->ValidUntil = sr_state->valid_until;
  573. sr_disk_state->ValidAfter = sr_state->valid_after;
  574. /* Shared random values. */
  575. next = &sr_disk_state->SharedRandValues;
  576. if (sr_state->previous_srv != NULL) {
  577. *next = line = tor_malloc_zero(sizeof(config_line_t));
  578. line->key = tor_strdup(dstate_prev_srv_key);
  579. disk_state_put_srv_line(sr_state->previous_srv, line);
  580. /* Go to the next shared random value. */
  581. next = &(line->next);
  582. }
  583. if (sr_state->current_srv != NULL) {
  584. *next = line = tor_malloc_zero(sizeof(*line));
  585. line->key = tor_strdup(dstate_cur_srv_key);
  586. disk_state_put_srv_line(sr_state->current_srv, line);
  587. }
  588. /* Parse the commits and construct config line(s). */
  589. next = &sr_disk_state->Commit;
  590. DIGESTMAP_FOREACH(sr_state->commits, key, sr_commit_t *, commit) {
  591. *next = line = tor_malloc_zero(sizeof(*line));
  592. line->key = tor_strdup(dstate_commit_key);
  593. disk_state_put_commit_line(commit, line);
  594. next = &(line->next);
  595. } DIGESTMAP_FOREACH_END;
  596. }
  597. /* Load state from disk and put it into our disk state. If the state passes
  598. * validation, our global state will be updated with it. Return 0 on
  599. * success. On error, -EINVAL is returned if the state on disk did contained
  600. * something malformed or is unreadable. -ENOENT is returned indicating that
  601. * the state file is either empty of non existing. */
  602. static int
  603. disk_state_load_from_disk(void)
  604. {
  605. int ret;
  606. char *fname;
  607. fname = get_datadir_fname(default_fname);
  608. ret = disk_state_load_from_disk_impl(fname);
  609. tor_free(fname);
  610. return ret;
  611. }
  612. /* Helper for disk_state_load_from_disk(). */
  613. STATIC int
  614. disk_state_load_from_disk_impl(const char *fname)
  615. {
  616. int ret;
  617. char *content = NULL;
  618. sr_state_t *parsed_state = NULL;
  619. sr_disk_state_t *disk_state = NULL;
  620. /* Read content of file so we can parse it. */
  621. if ((content = read_file_to_str(fname, 0, NULL)) == NULL) {
  622. log_warn(LD_FS, "SR: Unable to read SR state file %s",
  623. escaped(fname));
  624. ret = -errno;
  625. goto error;
  626. }
  627. {
  628. config_line_t *lines = NULL;
  629. char *errmsg = NULL;
  630. /* Every error in this code path will return EINVAL. */
  631. ret = -EINVAL;
  632. if (config_get_lines(content, &lines, 0) < 0) {
  633. config_free_lines(lines);
  634. goto error;
  635. }
  636. disk_state = disk_state_new(time(NULL));
  637. config_assign(&state_format, disk_state, lines, 0, &errmsg);
  638. config_free_lines(lines);
  639. if (errmsg) {
  640. log_warn(LD_DIR, "SR: Reading state error: %s", errmsg);
  641. tor_free(errmsg);
  642. goto error;
  643. }
  644. }
  645. /* So far so good, we've loaded our state file into our disk state. Let's
  646. * validate it and then parse it. */
  647. if (disk_state_validate(disk_state) < 0) {
  648. ret = -EINVAL;
  649. goto error;
  650. }
  651. parsed_state = disk_state_parse(disk_state);
  652. if (parsed_state == NULL) {
  653. ret = -EINVAL;
  654. goto error;
  655. }
  656. state_set(parsed_state);
  657. disk_state_set(disk_state);
  658. tor_free(content);
  659. log_info(LD_DIR, "SR: State loaded successfully from file %s", fname);
  660. return 0;
  661. error:
  662. disk_state_free(disk_state);
  663. tor_free(content);
  664. return ret;
  665. }
  666. /* Save the disk state to disk but before that update it from the current
  667. * state so we always have the latest. Return 0 on success else -1. */
  668. static int
  669. disk_state_save_to_disk(void)
  670. {
  671. int ret;
  672. char *state, *content = NULL, *fname = NULL;
  673. char tbuf[ISO_TIME_LEN + 1];
  674. time_t now = time(NULL);
  675. /* If we didn't have the opportunity to setup an internal disk state,
  676. * don't bother saving something to disk. */
  677. if (sr_disk_state == NULL) {
  678. ret = 0;
  679. goto done;
  680. }
  681. /* Make sure that our disk state is up to date with our memory state
  682. * before saving it to disk. */
  683. disk_state_update();
  684. state = config_dump(&state_format, NULL, sr_disk_state, 0, 0);
  685. format_local_iso_time(tbuf, now);
  686. tor_asprintf(&content,
  687. "# Tor shared random state file last generated on %s "
  688. "local time\n"
  689. "# Other times below are in UTC\n"
  690. "# Please *do not* edit this file.\n\n%s",
  691. tbuf, state);
  692. tor_free(state);
  693. fname = get_datadir_fname(default_fname);
  694. if (write_str_to_file(fname, content, 0) < 0) {
  695. log_warn(LD_FS, "SR: Unable to write SR state to file %s", fname);
  696. ret = -1;
  697. goto done;
  698. }
  699. ret = 0;
  700. log_debug(LD_DIR, "SR: Saved state to file %s", fname);
  701. done:
  702. tor_free(fname);
  703. tor_free(content);
  704. return ret;
  705. }
  706. /* Reset our state to prepare for a new protocol run. Once this returns, all
  707. * commits in the state will be removed and freed. */
  708. STATIC void
  709. reset_state_for_new_protocol_run(time_t valid_after)
  710. {
  711. tor_assert(sr_state);
  712. /* Keep counters in track */
  713. sr_state->n_reveal_rounds = 0;
  714. sr_state->n_commit_rounds = 0;
  715. sr_state->n_protocol_runs++;
  716. /* Reset valid-until */
  717. sr_state->valid_until = get_state_valid_until_time(valid_after);
  718. sr_state->valid_after = valid_after;
  719. /* We are in a new protocol run so cleanup commits. */
  720. sr_state_delete_commits();
  721. }
  722. /* This is the first round of the new protocol run starting at
  723. * <b>valid_after</b>. Do the necessary housekeeping. */
  724. STATIC void
  725. new_protocol_run(time_t valid_after)
  726. {
  727. sr_commit_t *our_commitment = NULL;
  728. /* Only compute the srv at the end of the reveal phase. */
  729. if (sr_state->phase == SR_PHASE_REVEAL) {
  730. /* We are about to compute a new shared random value that will be set in
  731. * our state as the current value so rotate values. */
  732. state_rotate_srv();
  733. /* Compute the shared randomness value of the day. */
  734. sr_compute_srv();
  735. }
  736. /* Prepare for the new protocol run by reseting the state */
  737. reset_state_for_new_protocol_run(valid_after);
  738. /* Do some logging */
  739. log_info(LD_DIR, "SR: Protocol run #%" PRIu64 " starting!",
  740. sr_state->n_protocol_runs);
  741. /* Generate fresh commitments for this protocol run */
  742. our_commitment = sr_generate_our_commit(valid_after,
  743. get_my_v3_authority_cert());
  744. if (our_commitment) {
  745. /* Add our commitment to our state. In case we are unable to create one
  746. * (highly unlikely), we won't vote for this protocol run since our
  747. * commitment won't be in our state. */
  748. sr_state_add_commit(our_commitment);
  749. }
  750. }
  751. /* Return 1 iff the <b>next_phase</b> is a phase transition from the current
  752. * phase that is it's different. */
  753. STATIC int
  754. is_phase_transition(sr_phase_t next_phase)
  755. {
  756. return sr_state->phase != next_phase;
  757. }
  758. /* Helper function: return a commit using the RSA fingerprint of the
  759. * authority or NULL if no such commit is known. */
  760. static sr_commit_t *
  761. state_query_get_commit(const char *rsa_fpr)
  762. {
  763. tor_assert(rsa_fpr);
  764. return digestmap_get(sr_state->commits, rsa_fpr);
  765. }
  766. /* Helper function: This handles the GET state action using an
  767. * <b>obj_type</b> and <b>data</b> needed for the action. */
  768. static void *
  769. state_query_get_(sr_state_object_t obj_type, const void *data)
  770. {
  771. void *obj = NULL;
  772. switch (obj_type) {
  773. case SR_STATE_OBJ_COMMIT:
  774. {
  775. obj = state_query_get_commit(data);
  776. break;
  777. }
  778. case SR_STATE_OBJ_COMMITS:
  779. obj = sr_state->commits;
  780. break;
  781. case SR_STATE_OBJ_CURSRV:
  782. obj = sr_state->current_srv;
  783. break;
  784. case SR_STATE_OBJ_PREVSRV:
  785. obj = sr_state->previous_srv;
  786. break;
  787. case SR_STATE_OBJ_PHASE:
  788. obj = &sr_state->phase;
  789. break;
  790. case SR_STATE_OBJ_VALID_AFTER:
  791. default:
  792. tor_assert(0);
  793. }
  794. return obj;
  795. }
  796. /* Helper function: This handles the PUT state action using an
  797. * <b>obj_type</b> and <b>data</b> needed for the action. */
  798. static void
  799. state_query_put_(sr_state_object_t obj_type, void *data)
  800. {
  801. switch (obj_type) {
  802. case SR_STATE_OBJ_COMMIT:
  803. {
  804. sr_commit_t *commit = data;
  805. tor_assert(commit);
  806. commit_add_to_state(commit, sr_state);
  807. break;
  808. }
  809. case SR_STATE_OBJ_CURSRV:
  810. sr_state->current_srv = (sr_srv_t *) data;
  811. break;
  812. case SR_STATE_OBJ_PREVSRV:
  813. sr_state->previous_srv = (sr_srv_t *) data;
  814. break;
  815. case SR_STATE_OBJ_VALID_AFTER:
  816. sr_state->valid_after = *((time_t *) data);
  817. break;
  818. /* It's not allowed to change the phase nor the full commitments map from
  819. * the state. The phase is decided during a strict process post voting and
  820. * the commits should be put individually. */
  821. case SR_STATE_OBJ_PHASE:
  822. case SR_STATE_OBJ_COMMITS:
  823. default:
  824. tor_assert(0);
  825. }
  826. }
  827. /* Helper function: This handles the DEL_ALL state action using an
  828. * <b>obj_type</b> and <b>data</b> needed for the action. */
  829. static void
  830. state_query_del_all_(sr_state_object_t obj_type)
  831. {
  832. switch (obj_type) {
  833. case SR_STATE_OBJ_COMMIT:
  834. {
  835. /* We are in a new protocol run so cleanup commitments. */
  836. DIGESTMAP_FOREACH_MODIFY(sr_state->commits, key, sr_commit_t *, c) {
  837. sr_commit_free(c);
  838. MAP_DEL_CURRENT(key);
  839. } DIGESTMAP_FOREACH_END;
  840. break;
  841. }
  842. /* The following object are _NOT_ suppose to be removed. */
  843. case SR_STATE_OBJ_CURSRV:
  844. case SR_STATE_OBJ_PREVSRV:
  845. case SR_STATE_OBJ_PHASE:
  846. case SR_STATE_OBJ_COMMITS:
  847. case SR_STATE_OBJ_VALID_AFTER:
  848. default:
  849. tor_assert(0);
  850. }
  851. }
  852. /* Helper function: This handles the DEL state action using an
  853. * <b>obj_type</b> and <b>data</b> needed for the action. */
  854. static void
  855. state_query_del_(sr_state_object_t obj_type, void *data)
  856. {
  857. (void) data;
  858. switch (obj_type) {
  859. case SR_STATE_OBJ_PREVSRV:
  860. tor_free(sr_state->previous_srv);
  861. break;
  862. case SR_STATE_OBJ_CURSRV:
  863. tor_free(sr_state->current_srv);
  864. break;
  865. case SR_STATE_OBJ_COMMIT:
  866. case SR_STATE_OBJ_COMMITS:
  867. case SR_STATE_OBJ_PHASE:
  868. case SR_STATE_OBJ_VALID_AFTER:
  869. default:
  870. tor_assert(0);
  871. }
  872. }
  873. /* Query state using an <b>action</b> for an object type <b>obj_type</b>.
  874. * The <b>data</b> pointer needs to point to an object that the action needs
  875. * to use and if anything is required to be returned, it is stored in
  876. * <b>out</b>.
  877. *
  878. * This mechanism exists so we have one single point where we synchronized
  879. * our memory state with our disk state for every actions that changes it.
  880. * We then trigger a write on disk immediately.
  881. *
  882. * This should be the only entry point to our memory state. It's used by all
  883. * our state accessors and should be in the future. */
  884. static void
  885. state_query(sr_state_action_t action, sr_state_object_t obj_type,
  886. void *data, void **out)
  887. {
  888. switch (action) {
  889. case SR_STATE_ACTION_GET:
  890. *out = state_query_get_(obj_type, data);
  891. break;
  892. case SR_STATE_ACTION_PUT:
  893. state_query_put_(obj_type, data);
  894. break;
  895. case SR_STATE_ACTION_DEL:
  896. state_query_del_(obj_type, data);
  897. break;
  898. case SR_STATE_ACTION_DEL_ALL:
  899. state_query_del_all_(obj_type);
  900. break;
  901. case SR_STATE_ACTION_SAVE:
  902. /* Only trigger a disk state save. */
  903. break;
  904. default:
  905. tor_assert(0);
  906. }
  907. /* If the action actually changes the state, immediately save it to disk.
  908. * The following will sync the state -> disk state and then save it. */
  909. if (action != SR_STATE_ACTION_GET) {
  910. disk_state_save_to_disk();
  911. }
  912. }
  913. /* Delete the current SRV value from the state freeing it and the value is set
  914. * to NULL meaning empty. */
  915. static void
  916. state_del_current_srv(void)
  917. {
  918. state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_CURSRV, NULL, NULL);
  919. }
  920. /* Delete the previous SRV value from the state freeing it and the value is
  921. * set to NULL meaning empty. */
  922. static void
  923. state_del_previous_srv(void)
  924. {
  925. state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_PREVSRV, NULL, NULL);
  926. }
  927. /* Rotate SRV value by freeing the previous value, assigning the current
  928. * value to the previous one and nullifying the current one. */
  929. STATIC void
  930. state_rotate_srv(void)
  931. {
  932. /* First delete previous SRV from the state. Object will be freed. */
  933. state_del_previous_srv();
  934. /* Set previous SRV with the current one. */
  935. sr_state_set_previous_srv(sr_state_get_current_srv());
  936. /* Nullify the current srv. */
  937. sr_state_set_current_srv(NULL);
  938. }
  939. /* Set valid after time in the our state. */
  940. void
  941. sr_state_set_valid_after(time_t valid_after)
  942. {
  943. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_VALID_AFTER,
  944. (void *) &valid_after, NULL);
  945. }
  946. /* Return the phase we are currently in according to our state. */
  947. sr_phase_t
  948. sr_state_get_phase(void)
  949. {
  950. void *ptr;
  951. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PHASE, NULL, &ptr);
  952. return *(sr_phase_t *) ptr;
  953. }
  954. /* Return the previous SRV value from our state. Value CAN be NULL. */
  955. const sr_srv_t *
  956. sr_state_get_previous_srv(void)
  957. {
  958. const sr_srv_t *srv;
  959. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PREVSRV, NULL,
  960. (void *) &srv);
  961. return srv;
  962. }
  963. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  964. * object ownership is transfered to the state object. */
  965. void
  966. sr_state_set_previous_srv(const sr_srv_t *srv)
  967. {
  968. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_PREVSRV, (void *) srv,
  969. NULL);
  970. }
  971. /* Return the current SRV value from our state. Value CAN be NULL. */
  972. const sr_srv_t *
  973. sr_state_get_current_srv(void)
  974. {
  975. const sr_srv_t *srv;
  976. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_CURSRV, NULL,
  977. (void *) &srv);
  978. return srv;
  979. }
  980. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  981. * object ownership is transfered to the state object. */
  982. void
  983. sr_state_set_current_srv(const sr_srv_t *srv)
  984. {
  985. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_CURSRV, (void *) srv,
  986. NULL);
  987. }
  988. /* Clean all the SRVs in our state. */
  989. void
  990. sr_state_clean_srvs(void)
  991. {
  992. /* Remove SRVs from state. They will be set to NULL as "empty". */
  993. state_del_previous_srv();
  994. state_del_current_srv();
  995. }
  996. /* Return a pointer to the commits map from our state. CANNOT be NULL. */
  997. digestmap_t *
  998. sr_state_get_commits(void)
  999. {
  1000. digestmap_t *commits;
  1001. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMITS,
  1002. NULL, (void *) &commits);
  1003. tor_assert(commits);
  1004. return commits;
  1005. }
  1006. /* Update the current SR state as needed for the upcoming voting round at
  1007. * <b>valid_after</b>. */
  1008. void
  1009. sr_state_update(time_t valid_after)
  1010. {
  1011. sr_phase_t next_phase;
  1012. tor_assert(sr_state);
  1013. /* Don't call this function twice in the same voting period. */
  1014. if (valid_after <= sr_state->valid_after) {
  1015. log_info(LD_DIR, "SR: Asked to update state twice. Ignoring.");
  1016. return;
  1017. }
  1018. /* Get phase of upcoming round. */
  1019. next_phase = get_sr_protocol_phase(valid_after);
  1020. /* If we are transitioning to a new protocol phase, prepare the stage. */
  1021. if (is_phase_transition(next_phase)) {
  1022. if (next_phase == SR_PHASE_COMMIT) {
  1023. /* Going into commit phase means we are starting a new protocol run. */
  1024. new_protocol_run(valid_after);
  1025. }
  1026. /* Set the new phase for this round */
  1027. sr_state->phase = next_phase;
  1028. } else if (sr_state->phase == SR_PHASE_COMMIT &&
  1029. digestmap_size(sr_state->commits) == 0) {
  1030. /* We are _NOT_ in a transition phase so if we are in the commit phase
  1031. * and have no commit, generate one. Chances are that we are booting up
  1032. * so let's have a commit in our state for the next voting period. */
  1033. sr_commit_t *our_commit =
  1034. sr_generate_our_commit(valid_after, get_my_v3_authority_cert());
  1035. if (our_commit) {
  1036. /* Add our commitment to our state. In case we are unable to create one
  1037. * (highly unlikely), we won't vote for this protocol run since our
  1038. * commitment won't be in our state. */
  1039. sr_state_add_commit(our_commit);
  1040. }
  1041. }
  1042. sr_state_set_valid_after(valid_after);
  1043. /* Count the current round */
  1044. if (sr_state->phase == SR_PHASE_COMMIT) {
  1045. /* invariant check: we've not entered reveal phase yet */
  1046. tor_assert(sr_state->n_reveal_rounds == 0);
  1047. sr_state->n_commit_rounds++;
  1048. } else {
  1049. sr_state->n_reveal_rounds++;
  1050. }
  1051. { /* Debugging. */
  1052. char tbuf[ISO_TIME_LEN + 1];
  1053. format_iso_time(tbuf, valid_after);
  1054. log_info(LD_DIR, "SR: State prepared for upcoming voting period (%s). "
  1055. "Upcoming phase is %s (counters: %d commit & %d reveal rounds).",
  1056. tbuf, get_phase_str(sr_state->phase),
  1057. sr_state->n_commit_rounds, sr_state->n_reveal_rounds);
  1058. }
  1059. }
  1060. /* Return commit object from the given authority digest <b>rsa_identity</b>.
  1061. * Return NULL if not found. */
  1062. sr_commit_t *
  1063. sr_state_get_commit(const char *rsa_identity)
  1064. {
  1065. sr_commit_t *commit;
  1066. tor_assert(rsa_identity);
  1067. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMIT,
  1068. (void *) rsa_identity, (void *) &commit);
  1069. return commit;
  1070. }
  1071. /* Add <b>commit</b> to the permanent state. The commit object ownership is
  1072. * transfered to the state so the caller MUST not free it. */
  1073. void
  1074. sr_state_add_commit(sr_commit_t *commit)
  1075. {
  1076. tor_assert(commit);
  1077. /* Put the commit to the global state. */
  1078. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_COMMIT,
  1079. (void *) commit, NULL);
  1080. log_debug(LD_DIR, "SR: Commit from %s has been added to our state.",
  1081. sr_commit_get_rsa_fpr(commit));
  1082. }
  1083. /* Remove all commits from our state. */
  1084. void
  1085. sr_state_delete_commits(void)
  1086. {
  1087. state_query(SR_STATE_ACTION_DEL_ALL, SR_STATE_OBJ_COMMIT, NULL, NULL);
  1088. }
  1089. /* Copy the reveal information from <b>commit</b> into <b>saved_commit</b>.
  1090. * This <b>saved_commit</b> MUST come from our current SR state. Once modified,
  1091. * the disk state is updated. */
  1092. void
  1093. sr_state_copy_reveal_info(sr_commit_t *saved_commit, const sr_commit_t *commit)
  1094. {
  1095. tor_assert(saved_commit);
  1096. tor_assert(commit);
  1097. saved_commit->reveal_ts = commit->reveal_ts;
  1098. memcpy(saved_commit->random_number, commit->random_number,
  1099. sizeof(saved_commit->random_number));
  1100. strlcpy(saved_commit->encoded_reveal, commit->encoded_reveal,
  1101. sizeof(saved_commit->encoded_reveal));
  1102. state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
  1103. log_debug(LD_DIR, "SR: Reveal value learned %s (for commit %s) from %s",
  1104. saved_commit->encoded_reveal, saved_commit->encoded_commit,
  1105. sr_commit_get_rsa_fpr(saved_commit));
  1106. }
  1107. /* Set the fresh SRV flag from our state. This doesn't need to trigger a
  1108. * disk state synchronization so we directly change the state. */
  1109. void
  1110. sr_state_set_fresh_srv(void)
  1111. {
  1112. sr_state->is_srv_fresh = 1;
  1113. }
  1114. /* Unset the fresh SRV flag from our state. This doesn't need to trigger a
  1115. * disk state synchronization so we directly change the state. */
  1116. void
  1117. sr_state_unset_fresh_srv(void)
  1118. {
  1119. sr_state->is_srv_fresh = 0;
  1120. }
  1121. /* Return the value of the fresh SRV flag. */
  1122. unsigned int
  1123. sr_state_srv_is_fresh(void)
  1124. {
  1125. return sr_state->is_srv_fresh;
  1126. }
  1127. /* Cleanup and free our disk and memory state. */
  1128. void
  1129. sr_state_free(void)
  1130. {
  1131. state_free(sr_state);
  1132. disk_state_free(sr_disk_state);
  1133. /* Nullify our global state. */
  1134. sr_state = NULL;
  1135. sr_disk_state = NULL;
  1136. }
  1137. /* Save our current state in memory to disk. */
  1138. void
  1139. sr_state_save(void)
  1140. {
  1141. /* Query a SAVE action on our current state so it's synced and saved. */
  1142. state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
  1143. }
  1144. /* Return 1 iff the state has been initialized that is it exists in memory.
  1145. * Return 0 otherwise. */
  1146. int
  1147. sr_state_is_initialized(void)
  1148. {
  1149. return sr_state == NULL ? 0 : 1;
  1150. }
  1151. /* Initialize the disk and memory state.
  1152. *
  1153. * If save_to_disk is set to 1, the state is immediately saved to disk after
  1154. * creation else it's not thus only kept in memory.
  1155. * If read_from_disk is set to 1, we try to load the state from the disk and
  1156. * if not found, a new state is created.
  1157. *
  1158. * Return 0 on success else a negative value on error. */
  1159. int
  1160. sr_state_init(int save_to_disk, int read_from_disk)
  1161. {
  1162. int ret = -ENOENT;
  1163. time_t now = time(NULL);
  1164. /* We shouldn't have those assigned. */
  1165. tor_assert(sr_disk_state == NULL);
  1166. tor_assert(sr_state == NULL);
  1167. /* First, try to load the state from disk. */
  1168. if (read_from_disk) {
  1169. ret = disk_state_load_from_disk();
  1170. }
  1171. if (ret < 0) {
  1172. switch (-ret) {
  1173. case EINVAL:
  1174. /* We have a state on disk but it contains something we couldn't parse
  1175. * or an invalid entry in the state file. Let's remove it since it's
  1176. * obviously unusable and replace it by an new fresh state below. */
  1177. case ENOENT:
  1178. {
  1179. /* No state on disk so allocate our states for the first time. */
  1180. sr_state_t *new_state = state_new(default_fname, now);
  1181. sr_disk_state_t *new_disk_state = disk_state_new(now);
  1182. state_set(new_state);
  1183. /* It's important to set our disk state pointer since the save call
  1184. * below uses it to synchronized it with our memory state. */
  1185. disk_state_set(new_disk_state);
  1186. /* No entry, let's save our new state to disk. */
  1187. if (save_to_disk && disk_state_save_to_disk() < 0) {
  1188. goto error;
  1189. }
  1190. break;
  1191. }
  1192. default:
  1193. /* Big problem. Not possible. */
  1194. tor_assert(0);
  1195. }
  1196. }
  1197. /* We have a state in memory, let's make sure it's updated for the current
  1198. * and next voting round. */
  1199. {
  1200. time_t valid_after = get_next_valid_after_time(now);
  1201. sr_state_update(valid_after);
  1202. }
  1203. return 0;
  1204. error:
  1205. return -1;
  1206. }
  1207. #ifdef TOR_UNIT_TESTS
  1208. /* Set the current phase of the protocol. Used only by unit tests. */
  1209. void
  1210. set_sr_phase(sr_phase_t phase)
  1211. {
  1212. tor_assert(sr_state);
  1213. sr_state->phase = phase;
  1214. }
  1215. /* Get the SR state. Used only by unit tests */
  1216. sr_state_t *
  1217. get_sr_state(void)
  1218. {
  1219. return sr_state;
  1220. }
  1221. #endif /* TOR_UNIT_TESTS */