shared_random_state.c 38 KB

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