shared_random_state.c 41 KB

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