shared_random_state.c 39 KB

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