shared_random_state.c 41 KB

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