shared_random_state.c 41 KB

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