shared_random_state.c 40 KB

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