shared_random_state.c 39 KB

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