shared_random_state.c 41 KB

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