shared_random_state.c 41 KB

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