shared_random_state.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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. continue;
  355. }
  356. /* We consider parseable commit from our disk state to be valid because
  357. * they need to be in the first place to get in there. */
  358. commit->valid = 1;
  359. /* Add commit to our state pointer. */
  360. commit_add_to_state(commit, state);
  361. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  362. smartlist_free(args);
  363. }
  364. return 0;
  365. error:
  366. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  367. smartlist_free(args);
  368. return -1;
  369. }
  370. /* Parse a share random value line from the disk state and save it to dst
  371. * which is an allocated srv object. Return 0 on success else -1. */
  372. static int
  373. disk_state_parse_srv(const char *value, sr_srv_t *dst)
  374. {
  375. int ret = -1;
  376. smartlist_t *args;
  377. sr_srv_t *srv;
  378. tor_assert(value);
  379. tor_assert(dst);
  380. args = smartlist_new();
  381. smartlist_split_string(args, value, " ",
  382. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  383. if (smartlist_len(args) < 2) {
  384. log_warn(LD_BUG, "SR: Too few arguments in shared random value. "
  385. "Line: %s", escaped(value));
  386. goto error;
  387. }
  388. srv = sr_parse_srv(args);
  389. if (srv == NULL) {
  390. goto error;
  391. }
  392. dst->num_reveals = srv->num_reveals;
  393. memcpy(dst->value, srv->value, sizeof(dst->value));
  394. tor_free(srv);
  395. ret = 0;
  396. error:
  397. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  398. smartlist_free(args);
  399. return ret;
  400. }
  401. /* Parse both SharedRandCurrentValue and SharedRandPreviousValue line from
  402. * the state. Return 0 on success else -1. */
  403. static int
  404. disk_state_parse_sr_values(sr_state_t *state,
  405. const sr_disk_state_t *disk_state)
  406. {
  407. /* Only one value per type (current or previous) is allowed so we keep
  408. * track of it with these flag. */
  409. unsigned int seen_previous = 0, seen_current = 0;
  410. config_line_t *line;
  411. sr_srv_t *srv = NULL;
  412. tor_assert(state);
  413. tor_assert(disk_state);
  414. for (line = disk_state->SharedRandValues; line; line = line->next) {
  415. if (line->value == NULL) {
  416. continue;
  417. }
  418. srv = tor_malloc_zero(sizeof(*srv));
  419. if (disk_state_parse_srv(line->value, srv) < 0) {
  420. log_warn(LD_BUG, "SR: Broken current SRV line in state %s",
  421. escaped(line->value));
  422. goto bad;
  423. }
  424. if (!strcasecmp(line->key, dstate_prev_srv_key)) {
  425. if (seen_previous) {
  426. log_warn(LD_DIR, "SR: Second previous SRV value seen. Bad state");
  427. goto bad;
  428. }
  429. state->previous_srv = srv;
  430. seen_previous = 1;
  431. } else if (!strcasecmp(line->key, dstate_cur_srv_key)) {
  432. if (seen_current) {
  433. log_warn(LD_DIR, "SR: Second current SRV value seen. Bad state");
  434. goto bad;
  435. }
  436. state->current_srv = srv;
  437. seen_current = 1;
  438. } else {
  439. /* Unknown key. Ignoring. */
  440. tor_free(srv);
  441. }
  442. }
  443. return 0;
  444. bad:
  445. tor_free(srv);
  446. return -1;
  447. }
  448. /* Parse the given disk state and set a newly allocated state. On success,
  449. * return that state else NULL. */
  450. static sr_state_t *
  451. disk_state_parse(const sr_disk_state_t *new_disk_state)
  452. {
  453. sr_state_t *new_state = state_new(default_fname, time(NULL));
  454. tor_assert(new_disk_state);
  455. new_state->version = new_disk_state->Version;
  456. new_state->valid_until = new_disk_state->ValidUntil;
  457. new_state->valid_after = new_disk_state->ValidAfter;
  458. /* Set our current phase according to the valid-after time in our disk
  459. * state. The disk state we are parsing contains everything for the phase
  460. * starting at valid_after so make sure our phase reflects that. */
  461. new_state->phase = get_sr_protocol_phase(new_state->valid_after);
  462. /* Parse the shared random values. */
  463. if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
  464. goto error;
  465. }
  466. /* Parse the commits. */
  467. if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
  468. goto error;
  469. }
  470. /* Great! This new state contains everything we had on disk. */
  471. return new_state;
  472. error:
  473. state_free(new_state);
  474. return NULL;
  475. }
  476. /* From a valid commit object and an allocated config line, set the line's
  477. * value to the state string representation of a commit. */
  478. static void
  479. disk_state_put_commit_line(const sr_commit_t *commit, config_line_t *line)
  480. {
  481. char *reveal_str = NULL;
  482. tor_assert(commit);
  483. tor_assert(line);
  484. if (!tor_mem_is_zero(commit->encoded_reveal,
  485. sizeof(commit->encoded_reveal))) {
  486. /* Add extra whitespace so we can format the line correctly. */
  487. tor_asprintf(&reveal_str, " %s", commit->encoded_reveal);
  488. }
  489. tor_asprintf(&line->value, "%u %s %s %s%s",
  490. SR_PROTO_VERSION,
  491. crypto_digest_algorithm_get_name(commit->alg),
  492. sr_commit_get_rsa_fpr(commit),
  493. commit->encoded_commit,
  494. reveal_str != NULL ? reveal_str : "");
  495. if (reveal_str != NULL) {
  496. memwipe(reveal_str, 0, strlen(reveal_str));
  497. tor_free(reveal_str);
  498. }
  499. }
  500. /* From a valid srv object and an allocated config line, set the line's
  501. * value to the state string representation of a shared random value. */
  502. static void
  503. disk_state_put_srv_line(const sr_srv_t *srv, config_line_t *line)
  504. {
  505. char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  506. tor_assert(line);
  507. /* No SRV value thus don't add the line. This is possible since we might
  508. * not have a current or previous SRV value in our state. */
  509. if (srv == NULL) {
  510. return;
  511. }
  512. sr_srv_encode(encoded, sizeof(encoded), srv);
  513. tor_asprintf(&line->value, "%" PRIu64 " %s", srv->num_reveals, encoded);
  514. }
  515. /* Reset disk state that is free allocated memory and zeroed the object. */
  516. static void
  517. disk_state_reset(void)
  518. {
  519. /* Free allocated memory */
  520. config_free_lines(sr_disk_state->Commit);
  521. config_free_lines(sr_disk_state->SharedRandValues);
  522. config_free_lines(sr_disk_state->ExtraLines);
  523. tor_free(sr_disk_state->TorVersion);
  524. /* Clean up the struct */
  525. memset(sr_disk_state, 0, sizeof(*sr_disk_state));
  526. /* Reset it with useful data */
  527. sr_disk_state->magic_ = SR_DISK_STATE_MAGIC;
  528. sr_disk_state->TorVersion = tor_strdup(get_version());
  529. }
  530. /* Update our disk state based on our global SR state. */
  531. static void
  532. disk_state_update(void)
  533. {
  534. config_line_t **next, *line;
  535. tor_assert(sr_disk_state);
  536. tor_assert(sr_state);
  537. /* Reset current disk state. */
  538. disk_state_reset();
  539. /* First, update elements that we don't need to do a construction. */
  540. sr_disk_state->Version = sr_state->version;
  541. sr_disk_state->ValidUntil = sr_state->valid_until;
  542. sr_disk_state->ValidAfter = sr_state->valid_after;
  543. /* Shared random values. */
  544. next = &sr_disk_state->SharedRandValues;
  545. if (sr_state->previous_srv != NULL) {
  546. *next = line = tor_malloc_zero(sizeof(config_line_t));
  547. line->key = tor_strdup(dstate_prev_srv_key);
  548. disk_state_put_srv_line(sr_state->previous_srv, line);
  549. /* Go to the next shared random value. */
  550. next = &(line->next);
  551. }
  552. if (sr_state->current_srv != NULL) {
  553. *next = line = tor_malloc_zero(sizeof(*line));
  554. line->key = tor_strdup(dstate_cur_srv_key);
  555. disk_state_put_srv_line(sr_state->current_srv, line);
  556. }
  557. /* Parse the commits and construct config line(s). */
  558. next = &sr_disk_state->Commit;
  559. DIGESTMAP_FOREACH(sr_state->commits, key, sr_commit_t *, commit) {
  560. *next = line = tor_malloc_zero(sizeof(*line));
  561. line->key = tor_strdup(dstate_commit_key);
  562. disk_state_put_commit_line(commit, line);
  563. next = &(line->next);
  564. } DIGESTMAP_FOREACH_END;
  565. }
  566. /* Load state from disk and put it into our disk state. If the state passes
  567. * validation, our global state will be updated with it. Return 0 on
  568. * success. On error, -EINVAL is returned if the state on disk did contained
  569. * something malformed or is unreadable. -ENOENT is returned indicating that
  570. * the state file is either empty of non existing. */
  571. static int
  572. disk_state_load_from_disk(void)
  573. {
  574. int ret;
  575. char *fname;
  576. fname = get_datadir_fname(default_fname);
  577. ret = disk_state_load_from_disk_impl(fname);
  578. tor_free(fname);
  579. return ret;
  580. }
  581. /* Helper for disk_state_load_from_disk(). */
  582. STATIC int
  583. disk_state_load_from_disk_impl(const char *fname)
  584. {
  585. int ret;
  586. char *content = NULL;
  587. sr_state_t *parsed_state = NULL;
  588. sr_disk_state_t *disk_state = NULL;
  589. /* Read content of file so we can parse it. */
  590. if ((content = read_file_to_str(fname, 0, NULL)) == NULL) {
  591. log_warn(LD_FS, "SR: Unable to read SR state file %s",
  592. escaped(fname));
  593. ret = -errno;
  594. goto error;
  595. }
  596. {
  597. config_line_t *lines = NULL;
  598. char *errmsg = NULL;
  599. /* Every error in this code path will return EINVAL. */
  600. ret = -EINVAL;
  601. if (config_get_lines(content, &lines, 0) < 0) {
  602. config_free_lines(lines);
  603. goto error;
  604. }
  605. disk_state = disk_state_new(time(NULL));
  606. config_assign(&state_format, disk_state, lines, 0, &errmsg);
  607. config_free_lines(lines);
  608. if (errmsg) {
  609. log_warn(LD_DIR, "SR: Reading state error: %s", errmsg);
  610. tor_free(errmsg);
  611. goto error;
  612. }
  613. }
  614. /* So far so good, we've loaded our state file into our disk state. Let's
  615. * validate it and then parse it. */
  616. if (disk_state_validate(disk_state) < 0) {
  617. ret = -EINVAL;
  618. goto error;
  619. }
  620. parsed_state = disk_state_parse(disk_state);
  621. if (parsed_state == NULL) {
  622. ret = -EINVAL;
  623. goto error;
  624. }
  625. state_set(parsed_state);
  626. disk_state_set(disk_state);
  627. tor_free(content);
  628. log_info(LD_DIR, "SR: State loaded successfully from file %s", fname);
  629. return 0;
  630. error:
  631. disk_state_free(disk_state);
  632. tor_free(content);
  633. return ret;
  634. }
  635. /* Save the disk state to disk but before that update it from the current
  636. * state so we always have the latest. Return 0 on success else -1. */
  637. static int
  638. disk_state_save_to_disk(void)
  639. {
  640. int ret;
  641. char *state, *content = NULL, *fname = NULL;
  642. char tbuf[ISO_TIME_LEN + 1];
  643. time_t now = time(NULL);
  644. /* If we didn't have the opportunity to setup an internal disk state,
  645. * don't bother saving something to disk. */
  646. if (sr_disk_state == NULL) {
  647. ret = 0;
  648. goto done;
  649. }
  650. /* Make sure that our disk state is up to date with our memory state
  651. * before saving it to disk. */
  652. disk_state_update();
  653. state = config_dump(&state_format, NULL, sr_disk_state, 0, 0);
  654. format_local_iso_time(tbuf, now);
  655. tor_asprintf(&content,
  656. "# Tor shared random state file last generated on %s "
  657. "local time\n"
  658. "# Other times below are in UTC\n"
  659. "# Please *do not* edit this file.\n\n%s",
  660. tbuf, state);
  661. tor_free(state);
  662. fname = get_datadir_fname(default_fname);
  663. if (write_str_to_file(fname, content, 0) < 0) {
  664. log_warn(LD_FS, "SR: Unable to write SR state to file %s", fname);
  665. ret = -1;
  666. goto done;
  667. }
  668. ret = 0;
  669. log_debug(LD_DIR, "SR: Saved state to file %s", fname);
  670. done:
  671. tor_free(fname);
  672. tor_free(content);
  673. return ret;
  674. }
  675. /* Reset our state to prepare for a new protocol run. Once this returns, all
  676. * commits in the state will be removed and freed. */
  677. STATIC void
  678. reset_state_for_new_protocol_run(time_t valid_after)
  679. {
  680. tor_assert(sr_state);
  681. /* Keep counters in track */
  682. sr_state->n_reveal_rounds = 0;
  683. sr_state->n_commit_rounds = 0;
  684. sr_state->n_protocol_runs++;
  685. /* Reset valid-until */
  686. sr_state->valid_until = get_state_valid_until_time(valid_after);
  687. sr_state->valid_after = valid_after;
  688. /* We are in a new protocol run so cleanup commits. */
  689. sr_state_delete_commits();
  690. }
  691. /* This is the first round of the new protocol run starting at
  692. * <b>valid_after</b>. Do the necessary housekeeping. */
  693. STATIC void
  694. new_protocol_run(time_t valid_after)
  695. {
  696. sr_commit_t *our_commitment = NULL;
  697. /* Only compute the srv at the end of the reveal phase. */
  698. if (sr_state->phase == SR_PHASE_REVEAL) {
  699. /* We are about to compute a new shared random value that will be set in
  700. * our state as the current value so rotate values. */
  701. state_rotate_srv();
  702. /* Compute the shared randomness value of the day. */
  703. sr_compute_srv();
  704. }
  705. /* Prepare for the new protocol run by reseting the state */
  706. reset_state_for_new_protocol_run(valid_after);
  707. /* Do some logging */
  708. log_info(LD_DIR, "SR: Protocol run #%" PRIu64 " starting!",
  709. sr_state->n_protocol_runs);
  710. /* Generate fresh commitments for this protocol run */
  711. our_commitment = sr_generate_our_commit(valid_after,
  712. get_my_v3_authority_cert());
  713. if (our_commitment) {
  714. /* Add our commitment to our state. In case we are unable to create one
  715. * (highly unlikely), we won't vote for this protocol run since our
  716. * commitment won't be in our state. */
  717. sr_state_add_commit(our_commitment);
  718. }
  719. }
  720. /* Return 1 iff the <b>next_phase</b> is a phase transition from the current
  721. * phase that is it's different. */
  722. STATIC int
  723. is_phase_transition(sr_phase_t next_phase)
  724. {
  725. return sr_state->phase != next_phase;
  726. }
  727. /* Helper function: return a commit using the RSA fingerprint of the
  728. * authority or NULL if no such commit is known. */
  729. static sr_commit_t *
  730. state_query_get_commit(const char *rsa_fpr)
  731. {
  732. tor_assert(rsa_fpr);
  733. return digestmap_get(sr_state->commits, rsa_fpr);
  734. }
  735. /* Helper function: This handles the GET state action using an
  736. * <b>obj_type</b> and <b>data</b> needed for the action. */
  737. static void *
  738. state_query_get_(sr_state_object_t obj_type, const void *data)
  739. {
  740. void *obj = NULL;
  741. switch (obj_type) {
  742. case SR_STATE_OBJ_COMMIT:
  743. {
  744. obj = state_query_get_commit(data);
  745. break;
  746. }
  747. case SR_STATE_OBJ_COMMITS:
  748. obj = sr_state->commits;
  749. break;
  750. case SR_STATE_OBJ_CURSRV:
  751. obj = sr_state->current_srv;
  752. break;
  753. case SR_STATE_OBJ_PREVSRV:
  754. obj = sr_state->previous_srv;
  755. break;
  756. case SR_STATE_OBJ_PHASE:
  757. obj = &sr_state->phase;
  758. break;
  759. case SR_STATE_OBJ_VALID_AFTER:
  760. default:
  761. tor_assert(0);
  762. }
  763. return obj;
  764. }
  765. /* Helper function: This handles the PUT state action using an
  766. * <b>obj_type</b> and <b>data</b> needed for the action. */
  767. static void
  768. state_query_put_(sr_state_object_t obj_type, void *data)
  769. {
  770. switch (obj_type) {
  771. case SR_STATE_OBJ_COMMIT:
  772. {
  773. sr_commit_t *commit = data;
  774. tor_assert(commit);
  775. commit_add_to_state(commit, sr_state);
  776. break;
  777. }
  778. case SR_STATE_OBJ_CURSRV:
  779. sr_state->current_srv = (sr_srv_t *) data;
  780. break;
  781. case SR_STATE_OBJ_PREVSRV:
  782. sr_state->previous_srv = (sr_srv_t *) data;
  783. break;
  784. case SR_STATE_OBJ_VALID_AFTER:
  785. sr_state->valid_after = *((time_t *) data);
  786. break;
  787. /* It's not allowed to change the phase nor the full commitments map from
  788. * the state. The phase is decided during a strict process post voting and
  789. * the commits should be put individually. */
  790. case SR_STATE_OBJ_PHASE:
  791. case SR_STATE_OBJ_COMMITS:
  792. default:
  793. tor_assert(0);
  794. }
  795. }
  796. /* Helper function: This handles the DEL_ALL state action using an
  797. * <b>obj_type</b> and <b>data</b> needed for the action. */
  798. static void
  799. state_query_del_all_(sr_state_object_t obj_type)
  800. {
  801. switch (obj_type) {
  802. case SR_STATE_OBJ_COMMIT:
  803. {
  804. /* We are in a new protocol run so cleanup commitments. */
  805. DIGESTMAP_FOREACH_MODIFY(sr_state->commits, key, sr_commit_t *, c) {
  806. sr_commit_free(c);
  807. MAP_DEL_CURRENT(key);
  808. } DIGESTMAP_FOREACH_END;
  809. break;
  810. }
  811. /* The following object are _NOT_ suppose to be removed. */
  812. case SR_STATE_OBJ_CURSRV:
  813. case SR_STATE_OBJ_PREVSRV:
  814. case SR_STATE_OBJ_PHASE:
  815. case SR_STATE_OBJ_COMMITS:
  816. case SR_STATE_OBJ_VALID_AFTER:
  817. default:
  818. tor_assert(0);
  819. }
  820. }
  821. /* Helper function: This handles the DEL state action using an
  822. * <b>obj_type</b> and <b>data</b> needed for the action. */
  823. static void
  824. state_query_del_(sr_state_object_t obj_type, void *data)
  825. {
  826. (void) data;
  827. switch (obj_type) {
  828. case SR_STATE_OBJ_PREVSRV:
  829. tor_free(sr_state->previous_srv);
  830. break;
  831. case SR_STATE_OBJ_CURSRV:
  832. tor_free(sr_state->current_srv);
  833. break;
  834. case SR_STATE_OBJ_COMMIT:
  835. case SR_STATE_OBJ_COMMITS:
  836. case SR_STATE_OBJ_PHASE:
  837. case SR_STATE_OBJ_VALID_AFTER:
  838. default:
  839. tor_assert(0);
  840. }
  841. }
  842. /* Query state using an <b>action</b> for an object type <b>obj_type</b>.
  843. * The <b>data</b> pointer needs to point to an object that the action needs
  844. * to use and if anything is required to be returned, it is stored in
  845. * <b>out</b>.
  846. *
  847. * This mechanism exists so we have one single point where we synchronized
  848. * our memory state with our disk state for every actions that changes it.
  849. * We then trigger a write on disk immediately.
  850. *
  851. * This should be the only entry point to our memory state. It's used by all
  852. * our state accessors and should be in the future. */
  853. static void
  854. state_query(sr_state_action_t action, sr_state_object_t obj_type,
  855. void *data, void **out)
  856. {
  857. switch (action) {
  858. case SR_STATE_ACTION_GET:
  859. *out = state_query_get_(obj_type, data);
  860. break;
  861. case SR_STATE_ACTION_PUT:
  862. state_query_put_(obj_type, data);
  863. break;
  864. case SR_STATE_ACTION_DEL:
  865. state_query_del_(obj_type, data);
  866. break;
  867. case SR_STATE_ACTION_DEL_ALL:
  868. state_query_del_all_(obj_type);
  869. break;
  870. case SR_STATE_ACTION_SAVE:
  871. /* Only trigger a disk state save. */
  872. break;
  873. default:
  874. tor_assert(0);
  875. }
  876. /* If the action actually changes the state, immediately save it to disk.
  877. * The following will sync the state -> disk state and then save it. */
  878. if (action != SR_STATE_ACTION_GET) {
  879. disk_state_save_to_disk();
  880. }
  881. }
  882. /* Delete the current SRV value from the state freeing it and the value is set
  883. * to NULL meaning empty. */
  884. static void
  885. state_del_current_srv(void)
  886. {
  887. state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_CURSRV, NULL, NULL);
  888. }
  889. /* Delete the previous SRV value from the state freeing it and the value is
  890. * set to NULL meaning empty. */
  891. static void
  892. state_del_previous_srv(void)
  893. {
  894. state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_PREVSRV, NULL, NULL);
  895. }
  896. /* Rotate SRV value by freeing the previous value, assigning the current
  897. * value to the previous one and nullifying the current one. */
  898. STATIC void
  899. state_rotate_srv(void)
  900. {
  901. /* First delete previous SRV from the state. Object will be freed. */
  902. state_del_previous_srv();
  903. /* Set previous SRV with the current one. */
  904. sr_state_set_previous_srv(sr_state_get_current_srv());
  905. /* Nullify the current srv. */
  906. sr_state_set_current_srv(NULL);
  907. }
  908. /* Set valid after time in the our state. */
  909. void
  910. sr_state_set_valid_after(time_t valid_after)
  911. {
  912. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_VALID_AFTER,
  913. (void *) &valid_after, NULL);
  914. }
  915. /* Return the phase we are currently in according to our state. */
  916. sr_phase_t
  917. sr_state_get_phase(void)
  918. {
  919. void *ptr;
  920. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PHASE, NULL, &ptr);
  921. return *(sr_phase_t *) ptr;
  922. }
  923. /* Return the previous SRV value from our state. Value CAN be NULL. */
  924. const sr_srv_t *
  925. sr_state_get_previous_srv(void)
  926. {
  927. const sr_srv_t *srv;
  928. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PREVSRV, NULL,
  929. (void *) &srv);
  930. return srv;
  931. }
  932. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  933. * object ownership is transfered to the state object. */
  934. void
  935. sr_state_set_previous_srv(const sr_srv_t *srv)
  936. {
  937. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_PREVSRV, (void *) srv,
  938. NULL);
  939. }
  940. /* Return the current SRV value from our state. Value CAN be NULL. */
  941. const sr_srv_t *
  942. sr_state_get_current_srv(void)
  943. {
  944. const sr_srv_t *srv;
  945. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_CURSRV, NULL,
  946. (void *) &srv);
  947. return srv;
  948. }
  949. /* Set the current SRV value from our state. Value CAN be NULL. The srv
  950. * object ownership is transfered to the state object. */
  951. void
  952. sr_state_set_current_srv(const sr_srv_t *srv)
  953. {
  954. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_CURSRV, (void *) srv,
  955. NULL);
  956. }
  957. /* Clean all the SRVs in our state. */
  958. void
  959. sr_state_clean_srvs(void)
  960. {
  961. /* Remove SRVs from state. They will be set to NULL as "empty". */
  962. state_del_previous_srv();
  963. state_del_current_srv();
  964. }
  965. /* Return a pointer to the commits map from our state. CANNOT be NULL. */
  966. digestmap_t *
  967. sr_state_get_commits(void)
  968. {
  969. digestmap_t *commits;
  970. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMITS,
  971. NULL, (void *) &commits);
  972. tor_assert(commits);
  973. return commits;
  974. }
  975. /* Update the current SR state as needed for the upcoming voting round at
  976. * <b>valid_after</b>. */
  977. void
  978. sr_state_update(time_t valid_after)
  979. {
  980. sr_phase_t next_phase;
  981. tor_assert(sr_state);
  982. /* Don't call this function twice in the same voting period. */
  983. if (valid_after <= sr_state->valid_after) {
  984. log_info(LD_DIR, "SR: Asked to update state twice. Ignoring.");
  985. return;
  986. }
  987. /* Get phase of upcoming round. */
  988. next_phase = get_sr_protocol_phase(valid_after);
  989. /* If we are transitioning to a new protocol phase, prepare the stage. */
  990. if (is_phase_transition(next_phase)) {
  991. if (next_phase == SR_PHASE_COMMIT) {
  992. /* Going into commit phase means we are starting a new protocol run. */
  993. new_protocol_run(valid_after);
  994. }
  995. /* Set the new phase for this round */
  996. sr_state->phase = next_phase;
  997. } else if (sr_state->phase == SR_PHASE_COMMIT &&
  998. digestmap_size(sr_state->commits) == 0) {
  999. /* We are _NOT_ in a transition phase so if we are in the commit phase
  1000. * and have no commit, generate one. Chances are that we are booting up
  1001. * so let's have a commit in our state for the next voting period. */
  1002. sr_commit_t *our_commit =
  1003. sr_generate_our_commit(valid_after, get_my_v3_authority_cert());
  1004. if (our_commit) {
  1005. /* Add our commitment to our state. In case we are unable to create one
  1006. * (highly unlikely), we won't vote for this protocol run since our
  1007. * commitment won't be in our state. */
  1008. sr_state_add_commit(our_commit);
  1009. }
  1010. }
  1011. sr_state_set_valid_after(valid_after);
  1012. /* Count the current round */
  1013. if (sr_state->phase == SR_PHASE_COMMIT) {
  1014. /* invariant check: we've not entered reveal phase yet */
  1015. tor_assert(sr_state->n_reveal_rounds == 0);
  1016. sr_state->n_commit_rounds++;
  1017. } else {
  1018. sr_state->n_reveal_rounds++;
  1019. }
  1020. { /* Debugging. */
  1021. char tbuf[ISO_TIME_LEN + 1];
  1022. format_iso_time(tbuf, valid_after);
  1023. log_info(LD_DIR, "SR: State prepared for upcoming voting period (%s). "
  1024. "Upcoming phase is %s (counters: %d commit & %d reveal rounds).",
  1025. tbuf, get_phase_str(sr_state->phase),
  1026. sr_state->n_commit_rounds, sr_state->n_reveal_rounds);
  1027. }
  1028. }
  1029. /* Return commit object from the given authority digest <b>rsa_identity</b>.
  1030. * Return NULL if not found. */
  1031. sr_commit_t *
  1032. sr_state_get_commit(const char *rsa_identity)
  1033. {
  1034. sr_commit_t *commit;
  1035. tor_assert(rsa_identity);
  1036. state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMIT,
  1037. (void *) rsa_identity, (void *) &commit);
  1038. return commit;
  1039. }
  1040. /* Add <b>commit</b> to the permanent state. The commit object ownership is
  1041. * transfered to the state so the caller MUST not free it. */
  1042. void
  1043. sr_state_add_commit(sr_commit_t *commit)
  1044. {
  1045. tor_assert(commit);
  1046. /* Put the commit to the global state. */
  1047. state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_COMMIT,
  1048. (void *) commit, NULL);
  1049. log_debug(LD_DIR, "SR: Commit from %s has been added to our state.",
  1050. sr_commit_get_rsa_fpr(commit));
  1051. }
  1052. /* Remove all commits from our state. */
  1053. void
  1054. sr_state_delete_commits(void)
  1055. {
  1056. state_query(SR_STATE_ACTION_DEL_ALL, SR_STATE_OBJ_COMMIT, NULL, NULL);
  1057. }
  1058. /* Copy the reveal information from <b>commit</b> into <b>saved_commit</b>.
  1059. * This <b>saved_commit</b> MUST come from our current SR state. Once modified,
  1060. * the disk state is updated. */
  1061. void
  1062. sr_state_copy_reveal_info(sr_commit_t *saved_commit, const sr_commit_t *commit)
  1063. {
  1064. tor_assert(saved_commit);
  1065. tor_assert(commit);
  1066. saved_commit->reveal_ts = commit->reveal_ts;
  1067. memcpy(saved_commit->random_number, commit->random_number,
  1068. sizeof(saved_commit->random_number));
  1069. strlcpy(saved_commit->encoded_reveal, commit->encoded_reveal,
  1070. sizeof(saved_commit->encoded_reveal));
  1071. state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
  1072. log_debug(LD_DIR, "SR: Reveal value learned %s (for commit %s) from %s",
  1073. saved_commit->encoded_reveal, saved_commit->encoded_commit,
  1074. sr_commit_get_rsa_fpr(saved_commit));
  1075. }
  1076. /* Set the fresh SRV flag from our state. This doesn't need to trigger a
  1077. * disk state synchronization so we directly change the state. */
  1078. void
  1079. sr_state_set_fresh_srv(void)
  1080. {
  1081. sr_state->is_srv_fresh = 1;
  1082. }
  1083. /* Unset the fresh SRV flag from our state. This doesn't need to trigger a
  1084. * disk state synchronization so we directly change the state. */
  1085. void
  1086. sr_state_unset_fresh_srv(void)
  1087. {
  1088. sr_state->is_srv_fresh = 0;
  1089. }
  1090. /* Return the value of the fresh SRV flag. */
  1091. unsigned int
  1092. sr_state_srv_is_fresh(void)
  1093. {
  1094. return sr_state->is_srv_fresh;
  1095. }
  1096. /* Cleanup and free our disk and memory state. */
  1097. void
  1098. sr_state_free(void)
  1099. {
  1100. state_free(sr_state);
  1101. disk_state_free(sr_disk_state);
  1102. /* Nullify our global state. */
  1103. sr_state = NULL;
  1104. sr_disk_state = NULL;
  1105. }
  1106. /* Save our current state in memory to disk. */
  1107. void
  1108. sr_state_save(void)
  1109. {
  1110. /* Query a SAVE action on our current state so it's synced and saved. */
  1111. state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
  1112. }
  1113. /* Return 1 iff the state has been initialized that is it exists in memory.
  1114. * Return 0 otherwise. */
  1115. int
  1116. sr_state_is_initialized(void)
  1117. {
  1118. return sr_state == NULL ? 0 : 1;
  1119. }
  1120. /* Initialize the disk and memory state.
  1121. *
  1122. * If save_to_disk is set to 1, the state is immediately saved to disk after
  1123. * creation else it's not thus only kept in memory.
  1124. * If read_from_disk is set to 1, we try to load the state from the disk and
  1125. * if not found, a new state is created.
  1126. *
  1127. * Return 0 on success else a negative value on error. */
  1128. int
  1129. sr_state_init(int save_to_disk, int read_from_disk)
  1130. {
  1131. int ret = -ENOENT;
  1132. time_t now = time(NULL);
  1133. /* We shouldn't have those assigned. */
  1134. tor_assert(sr_disk_state == NULL);
  1135. tor_assert(sr_state == NULL);
  1136. /* First, try to load the state from disk. */
  1137. if (read_from_disk) {
  1138. ret = disk_state_load_from_disk();
  1139. }
  1140. if (ret < 0) {
  1141. switch (-ret) {
  1142. case EINVAL:
  1143. /* We have a state on disk but it contains something we couldn't parse
  1144. * or an invalid entry in the state file. Let's remove it since it's
  1145. * obviously unusable and replace it by an new fresh state below. */
  1146. case ENOENT:
  1147. {
  1148. /* No state on disk so allocate our states for the first time. */
  1149. sr_state_t *new_state = state_new(default_fname, now);
  1150. sr_disk_state_t *new_disk_state = disk_state_new(now);
  1151. state_set(new_state);
  1152. /* It's important to set our disk state pointer since the save call
  1153. * below uses it to synchronized it with our memory state. */
  1154. disk_state_set(new_disk_state);
  1155. /* No entry, let's save our new state to disk. */
  1156. if (save_to_disk && disk_state_save_to_disk() < 0) {
  1157. goto error;
  1158. }
  1159. break;
  1160. }
  1161. default:
  1162. /* Big problem. Not possible. */
  1163. tor_assert(0);
  1164. }
  1165. }
  1166. /* We have a state in memory, let's make sure it's updated for the current
  1167. * and next voting round. */
  1168. {
  1169. time_t valid_after = get_next_valid_after_time(now);
  1170. sr_state_update(valid_after);
  1171. }
  1172. return 0;
  1173. error:
  1174. return -1;
  1175. }
  1176. #ifdef TOR_UNIT_TESTS
  1177. /* Set the current phase of the protocol. Used only by unit tests. */
  1178. void
  1179. set_sr_phase(sr_phase_t phase)
  1180. {
  1181. tor_assert(sr_state);
  1182. sr_state->phase = phase;
  1183. }
  1184. /* Get the SR state. Used only by unit tests */
  1185. sr_state_t *
  1186. get_sr_state(void)
  1187. {
  1188. return sr_state;
  1189. }
  1190. #endif /* TOR_UNIT_TESTS */