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