shared_random_state.c 39 KB

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