shared_random_state.c 41 KB

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