shared_random_state.c 40 KB

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