shared_random_state.c 38 KB

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