shared_random_state.c 39 KB

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