shared_random_state.c 40 KB

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