Cache control file
[tor/appveyor.git] / src / or / shared_random_state.c
blob53782af59a500127b6b09616c1a04c239e2f9a77
1 /* Copyright (c) 2016-2017, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file shared_random_state.c
7 * \brief Functions and data structures for the state of the random protocol
8 * as defined in proposal #250.
9 **/
11 #define SHARED_RANDOM_STATE_PRIVATE
13 #include "or.h"
14 #include "shared_random.h"
15 #include "config.h"
16 #include "confparse.h"
17 #include "dirvote.h"
18 #include "networkstatus.h"
19 #include "router.h"
20 #include "shared_random_state.h"
22 /* Default filename of the shared random state on disk. */
23 static const char default_fname[] = "sr-state";
25 /* String representation of a protocol phase. */
26 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;
33 /* Representation of our persistent state on disk. The sr_state above
34 * contains the data parsed from this state. When we save to disk, we
35 * translate the sr_state to this sr_disk_state. */
36 static sr_disk_state_t *sr_disk_state = NULL;
38 /* Disk state file keys. */
39 static const char dstate_commit_key[] = "Commit";
40 static const char dstate_prev_srv_key[] = "SharedRandPreviousValue";
41 static const char dstate_cur_srv_key[] = "SharedRandCurrentValue";
43 /** dummy instance of sr_disk_state_t, used for type-checking its
44 * members with CONF_CHECK_VAR_TYPE. */
45 DUMMY_TYPECHECK_INSTANCE(sr_disk_state_t);
47 /* These next two are duplicates or near-duplicates from config.c */
48 #define VAR(name, conftype, member, initvalue) \
49 { name, CONFIG_TYPE_ ## conftype, offsetof(sr_disk_state_t, member), \
50 initvalue CONF_TEST_MEMBERS(sr_disk_state_t, conftype, member) }
51 /* As VAR, but the option name and member name are the same. */
52 #define V(member, conftype, initvalue) \
53 VAR(#member, conftype, member, initvalue)
54 /* Our persistent state magic number. */
55 #define SR_DISK_STATE_MAGIC 0x98AB1254
56 /* Each protocol phase has 12 rounds */
57 #define SHARED_RANDOM_N_ROUNDS 12
58 /* Number of phase we have in a protocol. */
59 #define SHARED_RANDOM_N_PHASES 2
61 static int
62 disk_state_validate_cb(void *old_state, void *state, void *default_state,
63 int from_setconf, char **msg);
65 /* Array of variables that are saved to disk as a persistent state. */
66 static config_var_t state_vars[] = {
67 V(Version, UINT, "0"),
68 V(TorVersion, STRING, NULL),
69 V(ValidAfter, ISOTIME, NULL),
70 V(ValidUntil, ISOTIME, NULL),
72 V(Commit, LINELIST, NULL),
74 V(SharedRandValues, LINELIST_V, NULL),
75 VAR("SharedRandPreviousValue",LINELIST_S, SharedRandValues, NULL),
76 VAR("SharedRandCurrentValue", LINELIST_S, SharedRandValues, NULL),
77 END_OF_CONFIG_VARS
80 /* "Extra" variable in the state that receives lines we can't parse. This
81 * lets us preserve options from versions of Tor newer than us. */
82 static config_var_t state_extra_var = {
83 "__extra", CONFIG_TYPE_LINELIST,
84 offsetof(sr_disk_state_t, ExtraLines), NULL
85 CONF_TEST_MEMBERS(sr_disk_state_t, LINELIST, ExtraLines)
88 /* Configuration format of sr_disk_state_t. */
89 static const config_format_t state_format = {
90 sizeof(sr_disk_state_t),
91 SR_DISK_STATE_MAGIC,
92 offsetof(sr_disk_state_t, magic_),
93 NULL,
94 NULL,
95 state_vars,
96 disk_state_validate_cb,
97 &state_extra_var,
100 /* Return a string representation of a protocol phase. */
101 STATIC const char *
102 get_phase_str(sr_phase_t phase)
104 const char *the_string = NULL;
106 switch (phase) {
107 case SR_PHASE_COMMIT:
108 case SR_PHASE_REVEAL:
109 the_string = phase_str[phase];
110 break;
111 default:
112 /* Unknown phase shouldn't be possible. */
113 tor_assert(0);
116 return the_string;
119 /* Return the voting interval of the tor vote subsystem. */
120 static int
121 get_voting_interval(void)
123 int interval;
124 networkstatus_t *consensus = networkstatus_get_live_consensus(time(NULL));
126 if (consensus) {
127 interval = (int)(consensus->fresh_until - consensus->valid_after);
128 } else {
129 /* Same for both a testing and real network. We voluntarily ignore the
130 * InitialVotingInterval since it complexifies things and it doesn't
131 * affect the SR protocol. */
132 interval = get_options()->V3AuthVotingInterval;
134 tor_assert(interval > 0);
135 return interval;
138 /* Given the time <b>now</b>, return the start time of the current round of
139 * the SR protocol. For example, if it's 23:47:08, the current round thus
140 * started at 23:47:00 for a voting interval of 10 seconds. */
141 STATIC time_t
142 get_start_time_of_current_round(void)
144 const or_options_t *options = get_options();
145 int voting_interval = get_voting_interval();
146 /* First, get the start time of the next round */
147 time_t next_start = dirvote_get_next_valid_after_time();
148 /* Now roll back next_start by a voting interval to find the start time of
149 the current round. */
150 time_t curr_start = dirvote_get_start_of_next_interval(
151 next_start - voting_interval - 1,
152 voting_interval,
153 options->TestingV3AuthVotingStartOffset);
154 return curr_start;
157 /** Return the start time of the current SR protocol run. For example, if the
158 * time is 23/06/2017 23:47:08 and a full SR protocol run is 24 hours, this
159 * function should return 23/06/2017 00:00:00. */
160 time_t
161 sr_state_get_start_time_of_current_protocol_run(time_t now)
163 int total_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
164 int voting_interval = get_voting_interval();
165 /* Find the time the current round started. */
166 time_t beginning_of_current_round = get_start_time_of_current_round();
168 /* Get current SR protocol round */
169 int current_round = (now / voting_interval) % total_rounds;
171 /* Get start time by subtracting the time elapsed from the beginning of the
172 protocol run */
173 time_t time_elapsed_since_start_of_run = current_round * voting_interval;
174 return beginning_of_current_round - time_elapsed_since_start_of_run;
177 /** Return the time (in seconds) it takes to complete a full SR protocol phase
178 * (e.g. the commit phase). */
179 unsigned int
180 sr_state_get_phase_duration(void)
182 return SHARED_RANDOM_N_ROUNDS * get_voting_interval();
185 /** Return the time (in seconds) it takes to complete a full SR protocol run */
186 unsigned int
187 sr_state_get_protocol_run_duration(void)
189 int total_protocol_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
190 return total_protocol_rounds * get_voting_interval();
193 /* Return the time we should expire the state file created at <b>now</b>.
194 * We expire the state file in the beginning of the next protocol run. */
195 STATIC time_t
196 get_state_valid_until_time(time_t now)
198 int total_rounds = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
199 int current_round, voting_interval, rounds_left;
200 time_t valid_until, beginning_of_current_round;
202 voting_interval = get_voting_interval();
203 /* Find the time the current round started. */
204 beginning_of_current_round = get_start_time_of_current_round();
206 /* Find how many rounds are left till the end of the protocol run */
207 current_round = (now / voting_interval) % total_rounds;
208 rounds_left = total_rounds - current_round;
210 /* To find the valid-until time now, take the start time of the current
211 * round and add to it the time it takes for the leftover rounds to
212 * complete. */
213 valid_until = beginning_of_current_round + (rounds_left * voting_interval);
215 { /* Logging */
216 char tbuf[ISO_TIME_LEN + 1];
217 format_iso_time(tbuf, valid_until);
218 log_debug(LD_DIR, "SR: Valid until time for state set to %s.", tbuf);
221 return valid_until;
224 /* Given the consensus 'valid-after' time, return the protocol phase we should
225 * be in. */
226 STATIC sr_phase_t
227 get_sr_protocol_phase(time_t valid_after)
229 /* Shared random protocol has two phases, commit and reveal. */
230 int total_periods = SHARED_RANDOM_N_ROUNDS * SHARED_RANDOM_N_PHASES;
231 int current_slot;
233 /* Split time into slots of size 'voting_interval'. See which slot we are
234 * currently into, and find which phase it corresponds to. */
235 current_slot = (valid_after / get_voting_interval()) % total_periods;
237 if (current_slot < SHARED_RANDOM_N_ROUNDS) {
238 return SR_PHASE_COMMIT;
239 } else {
240 return SR_PHASE_REVEAL;
244 /* Add the given <b>commit</b> to <b>state</b>. It MUST be a valid commit
245 * and there shouldn't be a commit from the same authority in the state
246 * already else verification hasn't been done prior. This takes ownership of
247 * the commit once in our state. */
248 static void
249 commit_add_to_state(sr_commit_t *commit, sr_state_t *state)
251 sr_commit_t *saved_commit;
253 tor_assert(commit);
254 tor_assert(state);
256 saved_commit = digestmap_set(state->commits, commit->rsa_identity,
257 commit);
258 if (saved_commit != NULL) {
259 /* This means we already have that commit in our state so adding twice
260 * the same commit is either a code flow error, a corrupted disk state
261 * or some new unknown issue. */
262 log_warn(LD_DIR, "SR: Commit from %s exists in our state while "
263 "adding it: '%s'", sr_commit_get_rsa_fpr(commit),
264 commit->encoded_commit);
265 sr_commit_free(saved_commit);
269 /* Helper: deallocate a commit object. (Used with digestmap_free(), which
270 * requires a function pointer whose argument is void *). */
271 static void
272 commit_free_(void *p)
274 sr_commit_free_(p);
277 #define state_free(val) \
278 FREE_AND_NULL(sr_state_t, state_free_, (val))
280 /* Free a state that was allocated with state_new(). */
281 static void
282 state_free_(sr_state_t *state)
284 if (state == NULL) {
285 return;
287 tor_free(state->fname);
288 digestmap_free(state->commits, commit_free_);
289 tor_free(state->current_srv);
290 tor_free(state->previous_srv);
291 tor_free(state);
294 /* Allocate an sr_state_t object and returns it. If no <b>fname</b>, the
295 * default file name is used. This function does NOT initialize the state
296 * timestamp, phase or shared random value. NULL is never returned. */
297 static sr_state_t *
298 state_new(const char *fname, time_t now)
300 sr_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
301 /* If file name is not provided, use default. */
302 if (fname == NULL) {
303 fname = default_fname;
305 new_state->fname = tor_strdup(fname);
306 new_state->version = SR_PROTO_VERSION;
307 new_state->commits = digestmap_new();
308 new_state->phase = get_sr_protocol_phase(now);
309 new_state->valid_until = get_state_valid_until_time(now);
310 return new_state;
313 /* Set our global state pointer with the one given. */
314 static void
315 state_set(sr_state_t *state)
317 tor_assert(state);
318 if (sr_state != NULL) {
319 state_free(sr_state);
321 sr_state = state;
324 #define disk_state_free(val) \
325 FREE_AND_NULL(sr_disk_state_t, disk_state_free_, (val))
327 /* Free an allocated disk state. */
328 static void
329 disk_state_free_(sr_disk_state_t *state)
331 if (state == NULL) {
332 return;
334 config_free(&state_format, state);
337 /* Allocate a new disk state, initialize it and return it. */
338 static sr_disk_state_t *
339 disk_state_new(time_t now)
341 sr_disk_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
343 new_state->magic_ = SR_DISK_STATE_MAGIC;
344 new_state->Version = SR_PROTO_VERSION;
345 new_state->TorVersion = tor_strdup(get_version());
346 new_state->ValidUntil = get_state_valid_until_time(now);
347 new_state->ValidAfter = now;
349 /* Init config format. */
350 config_init(&state_format, new_state);
351 return new_state;
354 /* Set our global disk state with the given state. */
355 static void
356 disk_state_set(sr_disk_state_t *state)
358 tor_assert(state);
359 if (sr_disk_state != NULL) {
360 disk_state_free(sr_disk_state);
362 sr_disk_state = state;
365 /* Return -1 if the disk state is invalid (something in there that we can't or
366 * shouldn't use). Return 0 if everything checks out. */
367 static int
368 disk_state_validate(const sr_disk_state_t *state)
370 time_t now;
372 tor_assert(state);
374 /* Do we support the protocol version in the state or is it 0 meaning
375 * Version wasn't found in the state file or bad anyway ? */
376 if (state->Version == 0 || state->Version > SR_PROTO_VERSION) {
377 goto invalid;
380 /* If the valid until time is before now, we shouldn't use that state. */
381 now = time(NULL);
382 if (state->ValidUntil < now) {
383 log_info(LD_DIR, "SR: Disk state has expired. Ignoring it.");
384 goto invalid;
387 /* Make sure we don't have a valid after time that is earlier than a valid
388 * until time which would make things not work well. */
389 if (state->ValidAfter >= state->ValidUntil) {
390 log_info(LD_DIR, "SR: Disk state valid after/until times are invalid.");
391 goto invalid;
394 return 0;
396 invalid:
397 return -1;
400 /* Validate the disk state (NOP for now). */
401 static int
402 disk_state_validate_cb(void *old_state, void *state, void *default_state,
403 int from_setconf, char **msg)
405 /* We don't use these; only options do. */
406 (void) from_setconf;
407 (void) default_state;
408 (void) old_state;
410 /* This is called by config_dump which is just before we are about to
411 * write it to disk. At that point, our global memory state has been
412 * copied to the disk state so it's fair to assume it's trustable. */
413 (void) state;
414 (void) msg;
415 return 0;
418 /* Parse the Commit line(s) in the disk state and translate them to the
419 * the memory state. Return 0 on success else -1 on error. */
420 static int
421 disk_state_parse_commits(sr_state_t *state,
422 const sr_disk_state_t *disk_state)
424 config_line_t *line;
425 smartlist_t *args = NULL;
427 tor_assert(state);
428 tor_assert(disk_state);
430 for (line = disk_state->Commit; line; line = line->next) {
431 sr_commit_t *commit = NULL;
433 /* Extra safety. */
434 if (strcasecmp(line->key, dstate_commit_key) ||
435 line->value == NULL) {
436 /* Ignore any lines that are not commits. */
437 tor_fragile_assert();
438 continue;
440 args = smartlist_new();
441 smartlist_split_string(args, line->value, " ",
442 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
443 if (smartlist_len(args) < 3) {
444 log_warn(LD_BUG, "SR: Too few arguments in Commit Line: %s",
445 escaped(line->value));
446 goto error;
448 commit = sr_parse_commit(args);
449 if (commit == NULL) {
450 /* Ignore badly formed commit. It could also be a authority
451 * fingerprint that we don't know about so it shouldn't be used. */
452 continue;
454 /* We consider parseable commit from our disk state to be valid because
455 * they need to be in the first place to get in there. */
456 commit->valid = 1;
457 /* Add commit to our state pointer. */
458 commit_add_to_state(commit, state);
460 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
461 smartlist_free(args);
464 return 0;
466 error:
467 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
468 smartlist_free(args);
469 return -1;
472 /* Parse a share random value line from the disk state and save it to dst
473 * which is an allocated srv object. Return 0 on success else -1. */
474 static int
475 disk_state_parse_srv(const char *value, sr_srv_t *dst)
477 int ret = -1;
478 smartlist_t *args;
479 sr_srv_t *srv;
481 tor_assert(value);
482 tor_assert(dst);
484 args = smartlist_new();
485 smartlist_split_string(args, value, " ",
486 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
487 if (smartlist_len(args) < 2) {
488 log_warn(LD_BUG, "SR: Too few arguments in shared random value. "
489 "Line: %s", escaped(value));
490 goto error;
492 srv = sr_parse_srv(args);
493 if (srv == NULL) {
494 goto error;
496 dst->num_reveals = srv->num_reveals;
497 memcpy(dst->value, srv->value, sizeof(dst->value));
498 tor_free(srv);
499 ret = 0;
501 error:
502 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
503 smartlist_free(args);
504 return ret;
507 /* Parse both SharedRandCurrentValue and SharedRandPreviousValue line from
508 * the state. Return 0 on success else -1. */
509 static int
510 disk_state_parse_sr_values(sr_state_t *state,
511 const sr_disk_state_t *disk_state)
513 /* Only one value per type (current or previous) is allowed so we keep
514 * track of it with these flag. */
515 unsigned int seen_previous = 0, seen_current = 0;
516 config_line_t *line;
517 sr_srv_t *srv = NULL;
519 tor_assert(state);
520 tor_assert(disk_state);
522 for (line = disk_state->SharedRandValues; line; line = line->next) {
523 if (line->value == NULL) {
524 continue;
526 srv = tor_malloc_zero(sizeof(*srv));
527 if (disk_state_parse_srv(line->value, srv) < 0) {
528 log_warn(LD_BUG, "SR: Broken current SRV line in state %s",
529 escaped(line->value));
530 goto bad;
532 if (!strcasecmp(line->key, dstate_prev_srv_key)) {
533 if (seen_previous) {
534 log_warn(LD_DIR, "SR: Second previous SRV value seen. Bad state");
535 goto bad;
537 state->previous_srv = srv;
538 seen_previous = 1;
539 } else if (!strcasecmp(line->key, dstate_cur_srv_key)) {
540 if (seen_current) {
541 log_warn(LD_DIR, "SR: Second current SRV value seen. Bad state");
542 goto bad;
544 state->current_srv = srv;
545 seen_current = 1;
546 } else {
547 /* Unknown key. Ignoring. */
548 tor_free(srv);
552 return 0;
553 bad:
554 tor_free(srv);
555 return -1;
558 /* Parse the given disk state and set a newly allocated state. On success,
559 * return that state else NULL. */
560 static sr_state_t *
561 disk_state_parse(const sr_disk_state_t *new_disk_state)
563 sr_state_t *new_state = state_new(default_fname, time(NULL));
565 tor_assert(new_disk_state);
567 new_state->version = new_disk_state->Version;
568 new_state->valid_until = new_disk_state->ValidUntil;
569 new_state->valid_after = new_disk_state->ValidAfter;
571 /* Set our current phase according to the valid-after time in our disk
572 * state. The disk state we are parsing contains everything for the phase
573 * starting at valid_after so make sure our phase reflects that. */
574 new_state->phase = get_sr_protocol_phase(new_state->valid_after);
576 /* Parse the shared random values. */
577 if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
578 goto error;
580 /* Parse the commits. */
581 if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
582 goto error;
584 /* Great! This new state contains everything we had on disk. */
585 return new_state;
587 error:
588 state_free(new_state);
589 return NULL;
592 /* From a valid commit object and an allocated config line, set the line's
593 * value to the state string representation of a commit. */
594 static void
595 disk_state_put_commit_line(const sr_commit_t *commit, config_line_t *line)
597 char *reveal_str = NULL;
599 tor_assert(commit);
600 tor_assert(line);
602 if (!tor_mem_is_zero(commit->encoded_reveal,
603 sizeof(commit->encoded_reveal))) {
604 /* Add extra whitespace so we can format the line correctly. */
605 tor_asprintf(&reveal_str, " %s", commit->encoded_reveal);
607 tor_asprintf(&line->value, "%u %s %s %s%s",
608 SR_PROTO_VERSION,
609 crypto_digest_algorithm_get_name(commit->alg),
610 sr_commit_get_rsa_fpr(commit),
611 commit->encoded_commit,
612 reveal_str != NULL ? reveal_str : "");
613 if (reveal_str != NULL) {
614 memwipe(reveal_str, 0, strlen(reveal_str));
615 tor_free(reveal_str);
619 /* From a valid srv object and an allocated config line, set the line's
620 * value to the state string representation of a shared random value. */
621 static void
622 disk_state_put_srv_line(const sr_srv_t *srv, config_line_t *line)
624 char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
626 tor_assert(line);
628 /* No SRV value thus don't add the line. This is possible since we might
629 * not have a current or previous SRV value in our state. */
630 if (srv == NULL) {
631 return;
633 sr_srv_encode(encoded, sizeof(encoded), srv);
634 tor_asprintf(&line->value, "%" PRIu64 " %s", srv->num_reveals, encoded);
637 /* Reset disk state that is free allocated memory and zeroed the object. */
638 static void
639 disk_state_reset(void)
641 /* Free allocated memory */
642 config_free_lines(sr_disk_state->Commit);
643 config_free_lines(sr_disk_state->SharedRandValues);
644 config_free_lines(sr_disk_state->ExtraLines);
645 tor_free(sr_disk_state->TorVersion);
647 /* Clean up the struct */
648 memset(sr_disk_state, 0, sizeof(*sr_disk_state));
650 /* Reset it with useful data */
651 sr_disk_state->magic_ = SR_DISK_STATE_MAGIC;
652 sr_disk_state->TorVersion = tor_strdup(get_version());
655 /* Update our disk state based on our global SR state. */
656 static void
657 disk_state_update(void)
659 config_line_t **next, *line;
661 tor_assert(sr_disk_state);
662 tor_assert(sr_state);
664 /* Reset current disk state. */
665 disk_state_reset();
667 /* First, update elements that we don't need to do a construction. */
668 sr_disk_state->Version = sr_state->version;
669 sr_disk_state->ValidUntil = sr_state->valid_until;
670 sr_disk_state->ValidAfter = sr_state->valid_after;
672 /* Shared random values. */
673 next = &sr_disk_state->SharedRandValues;
674 if (sr_state->previous_srv != NULL) {
675 *next = line = tor_malloc_zero(sizeof(config_line_t));
676 line->key = tor_strdup(dstate_prev_srv_key);
677 disk_state_put_srv_line(sr_state->previous_srv, line);
678 /* Go to the next shared random value. */
679 next = &(line->next);
681 if (sr_state->current_srv != NULL) {
682 *next = line = tor_malloc_zero(sizeof(*line));
683 line->key = tor_strdup(dstate_cur_srv_key);
684 disk_state_put_srv_line(sr_state->current_srv, line);
687 /* Parse the commits and construct config line(s). */
688 next = &sr_disk_state->Commit;
689 DIGESTMAP_FOREACH(sr_state->commits, key, sr_commit_t *, commit) {
690 *next = line = tor_malloc_zero(sizeof(*line));
691 line->key = tor_strdup(dstate_commit_key);
692 disk_state_put_commit_line(commit, line);
693 next = &(line->next);
694 } DIGESTMAP_FOREACH_END;
697 /* Load state from disk and put it into our disk state. If the state passes
698 * validation, our global state will be updated with it. Return 0 on
699 * success. On error, -EINVAL is returned if the state on disk did contained
700 * something malformed or is unreadable. -ENOENT is returned indicating that
701 * the state file is either empty of non existing. */
702 static int
703 disk_state_load_from_disk(void)
705 int ret;
706 char *fname;
708 fname = get_datadir_fname(default_fname);
709 ret = disk_state_load_from_disk_impl(fname);
710 tor_free(fname);
712 return ret;
715 /* Helper for disk_state_load_from_disk(). */
716 STATIC int
717 disk_state_load_from_disk_impl(const char *fname)
719 int ret;
720 char *content = NULL;
721 sr_state_t *parsed_state = NULL;
722 sr_disk_state_t *disk_state = NULL;
724 /* Read content of file so we can parse it. */
725 if ((content = read_file_to_str(fname, 0, NULL)) == NULL) {
726 log_warn(LD_FS, "SR: Unable to read SR state file %s",
727 escaped(fname));
728 ret = -errno;
729 goto error;
733 config_line_t *lines = NULL;
734 char *errmsg = NULL;
736 /* Every error in this code path will return EINVAL. */
737 ret = -EINVAL;
738 if (config_get_lines(content, &lines, 0) < 0) {
739 config_free_lines(lines);
740 goto error;
743 disk_state = disk_state_new(time(NULL));
744 config_assign(&state_format, disk_state, lines, 0, &errmsg);
745 config_free_lines(lines);
746 if (errmsg) {
747 log_warn(LD_DIR, "SR: Reading state error: %s", errmsg);
748 tor_free(errmsg);
749 goto error;
753 /* So far so good, we've loaded our state file into our disk state. Let's
754 * validate it and then parse it. */
755 if (disk_state_validate(disk_state) < 0) {
756 ret = -EINVAL;
757 goto error;
760 parsed_state = disk_state_parse(disk_state);
761 if (parsed_state == NULL) {
762 ret = -EINVAL;
763 goto error;
765 state_set(parsed_state);
766 disk_state_set(disk_state);
767 tor_free(content);
768 log_info(LD_DIR, "SR: State loaded successfully from file %s", fname);
769 return 0;
771 error:
772 disk_state_free(disk_state);
773 tor_free(content);
774 return ret;
777 /* Save the disk state to disk but before that update it from the current
778 * state so we always have the latest. Return 0 on success else -1. */
779 static int
780 disk_state_save_to_disk(void)
782 int ret;
783 char *state, *content = NULL, *fname = NULL;
784 char tbuf[ISO_TIME_LEN + 1];
785 time_t now = time(NULL);
787 /* If we didn't have the opportunity to setup an internal disk state,
788 * don't bother saving something to disk. */
789 if (sr_disk_state == NULL) {
790 ret = 0;
791 goto done;
794 /* Make sure that our disk state is up to date with our memory state
795 * before saving it to disk. */
796 disk_state_update();
797 state = config_dump(&state_format, NULL, sr_disk_state, 0, 0);
798 format_local_iso_time(tbuf, now);
799 tor_asprintf(&content,
800 "# Tor shared random state file last generated on %s "
801 "local time\n"
802 "# Other times below are in UTC\n"
803 "# Please *do not* edit this file.\n\n%s",
804 tbuf, state);
805 tor_free(state);
806 fname = get_datadir_fname(default_fname);
807 if (write_str_to_file(fname, content, 0) < 0) {
808 log_warn(LD_FS, "SR: Unable to write SR state to file %s", fname);
809 ret = -1;
810 goto done;
812 ret = 0;
813 log_debug(LD_DIR, "SR: Saved state to file %s", fname);
815 done:
816 tor_free(fname);
817 tor_free(content);
818 return ret;
821 /* Reset our state to prepare for a new protocol run. Once this returns, all
822 * commits in the state will be removed and freed. */
823 STATIC void
824 reset_state_for_new_protocol_run(time_t valid_after)
826 tor_assert(sr_state);
828 /* Keep counters in track */
829 sr_state->n_reveal_rounds = 0;
830 sr_state->n_commit_rounds = 0;
831 sr_state->n_protocol_runs++;
833 /* Reset valid-until */
834 sr_state->valid_until = get_state_valid_until_time(valid_after);
835 sr_state->valid_after = valid_after;
837 /* We are in a new protocol run so cleanup commits. */
838 sr_state_delete_commits();
841 /* This is the first round of the new protocol run starting at
842 * <b>valid_after</b>. Do the necessary housekeeping. */
843 STATIC void
844 new_protocol_run(time_t valid_after)
846 sr_commit_t *our_commitment = NULL;
848 /* Only compute the srv at the end of the reveal phase. */
849 if (sr_state->phase == SR_PHASE_REVEAL) {
850 /* We are about to compute a new shared random value that will be set in
851 * our state as the current value so rotate values. */
852 state_rotate_srv();
853 /* Compute the shared randomness value of the day. */
854 sr_compute_srv();
857 /* Prepare for the new protocol run by reseting the state */
858 reset_state_for_new_protocol_run(valid_after);
860 /* Do some logging */
861 log_info(LD_DIR, "SR: Protocol run #%" PRIu64 " starting!",
862 sr_state->n_protocol_runs);
864 /* Generate fresh commitments for this protocol run */
865 our_commitment = sr_generate_our_commit(valid_after,
866 get_my_v3_authority_cert());
867 if (our_commitment) {
868 /* Add our commitment to our state. In case we are unable to create one
869 * (highly unlikely), we won't vote for this protocol run since our
870 * commitment won't be in our state. */
871 sr_state_add_commit(our_commitment);
875 /* Return 1 iff the <b>next_phase</b> is a phase transition from the current
876 * phase that is it's different. */
877 STATIC int
878 is_phase_transition(sr_phase_t next_phase)
880 return sr_state->phase != next_phase;
883 /* Helper function: return a commit using the RSA fingerprint of the
884 * authority or NULL if no such commit is known. */
885 static sr_commit_t *
886 state_query_get_commit(const char *rsa_fpr)
888 tor_assert(rsa_fpr);
889 return digestmap_get(sr_state->commits, rsa_fpr);
892 /* Helper function: This handles the GET state action using an
893 * <b>obj_type</b> and <b>data</b> needed for the action. */
894 static void *
895 state_query_get_(sr_state_object_t obj_type, const void *data)
897 void *obj = NULL;
899 switch (obj_type) {
900 case SR_STATE_OBJ_COMMIT:
902 obj = state_query_get_commit(data);
903 break;
905 case SR_STATE_OBJ_COMMITS:
906 obj = sr_state->commits;
907 break;
908 case SR_STATE_OBJ_CURSRV:
909 obj = sr_state->current_srv;
910 break;
911 case SR_STATE_OBJ_PREVSRV:
912 obj = sr_state->previous_srv;
913 break;
914 case SR_STATE_OBJ_PHASE:
915 obj = &sr_state->phase;
916 break;
917 case SR_STATE_OBJ_VALID_AFTER:
918 default:
919 tor_assert(0);
921 return obj;
924 /* Helper function: This handles the PUT state action using an
925 * <b>obj_type</b> and <b>data</b> needed for the action. */
926 static void
927 state_query_put_(sr_state_object_t obj_type, void *data)
929 switch (obj_type) {
930 case SR_STATE_OBJ_COMMIT:
932 sr_commit_t *commit = data;
933 tor_assert(commit);
934 commit_add_to_state(commit, sr_state);
935 break;
937 case SR_STATE_OBJ_CURSRV:
938 sr_state->current_srv = (sr_srv_t *) data;
939 break;
940 case SR_STATE_OBJ_PREVSRV:
941 sr_state->previous_srv = (sr_srv_t *) data;
942 break;
943 case SR_STATE_OBJ_VALID_AFTER:
944 sr_state->valid_after = *((time_t *) data);
945 break;
946 /* It's not allowed to change the phase nor the full commitments map from
947 * the state. The phase is decided during a strict process post voting and
948 * the commits should be put individually. */
949 case SR_STATE_OBJ_PHASE:
950 case SR_STATE_OBJ_COMMITS:
951 default:
952 tor_assert(0);
956 /* Helper function: This handles the DEL_ALL state action using an
957 * <b>obj_type</b> and <b>data</b> needed for the action. */
958 static void
959 state_query_del_all_(sr_state_object_t obj_type)
961 switch (obj_type) {
962 case SR_STATE_OBJ_COMMIT:
964 /* We are in a new protocol run so cleanup commitments. */
965 DIGESTMAP_FOREACH_MODIFY(sr_state->commits, key, sr_commit_t *, c) {
966 sr_commit_free(c);
967 MAP_DEL_CURRENT(key);
968 } DIGESTMAP_FOREACH_END;
969 break;
971 /* The following object are _NOT_ suppose to be removed. */
972 case SR_STATE_OBJ_CURSRV:
973 case SR_STATE_OBJ_PREVSRV:
974 case SR_STATE_OBJ_PHASE:
975 case SR_STATE_OBJ_COMMITS:
976 case SR_STATE_OBJ_VALID_AFTER:
977 default:
978 tor_assert(0);
982 /* Helper function: This handles the DEL state action using an
983 * <b>obj_type</b> and <b>data</b> needed for the action. */
984 static void
985 state_query_del_(sr_state_object_t obj_type, void *data)
987 (void) data;
989 switch (obj_type) {
990 case SR_STATE_OBJ_PREVSRV:
991 tor_free(sr_state->previous_srv);
992 break;
993 case SR_STATE_OBJ_CURSRV:
994 tor_free(sr_state->current_srv);
995 break;
996 case SR_STATE_OBJ_COMMIT:
997 case SR_STATE_OBJ_COMMITS:
998 case SR_STATE_OBJ_PHASE:
999 case SR_STATE_OBJ_VALID_AFTER:
1000 default:
1001 tor_assert(0);
1005 /* Query state using an <b>action</b> for an object type <b>obj_type</b>.
1006 * The <b>data</b> pointer needs to point to an object that the action needs
1007 * to use and if anything is required to be returned, it is stored in
1008 * <b>out</b>.
1010 * This mechanism exists so we have one single point where we synchronized
1011 * our memory state with our disk state for every actions that changes it.
1012 * We then trigger a write on disk immediately.
1014 * This should be the only entry point to our memory state. It's used by all
1015 * our state accessors and should be in the future. */
1016 static void
1017 state_query(sr_state_action_t action, sr_state_object_t obj_type,
1018 void *data, void **out)
1020 switch (action) {
1021 case SR_STATE_ACTION_GET:
1022 *out = state_query_get_(obj_type, data);
1023 break;
1024 case SR_STATE_ACTION_PUT:
1025 state_query_put_(obj_type, data);
1026 break;
1027 case SR_STATE_ACTION_DEL:
1028 state_query_del_(obj_type, data);
1029 break;
1030 case SR_STATE_ACTION_DEL_ALL:
1031 state_query_del_all_(obj_type);
1032 break;
1033 case SR_STATE_ACTION_SAVE:
1034 /* Only trigger a disk state save. */
1035 break;
1036 default:
1037 tor_assert(0);
1040 /* If the action actually changes the state, immediately save it to disk.
1041 * The following will sync the state -> disk state and then save it. */
1042 if (action != SR_STATE_ACTION_GET) {
1043 disk_state_save_to_disk();
1047 /* Delete the current SRV value from the state freeing it and the value is set
1048 * to NULL meaning empty. */
1049 static void
1050 state_del_current_srv(void)
1052 state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_CURSRV, NULL, NULL);
1055 /* Delete the previous SRV value from the state freeing it and the value is
1056 * set to NULL meaning empty. */
1057 static void
1058 state_del_previous_srv(void)
1060 state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_PREVSRV, NULL, NULL);
1063 /* Rotate SRV value by freeing the previous value, assigning the current
1064 * value to the previous one and nullifying the current one. */
1065 STATIC void
1066 state_rotate_srv(void)
1068 /* First delete previous SRV from the state. Object will be freed. */
1069 state_del_previous_srv();
1070 /* Set previous SRV with the current one. */
1071 sr_state_set_previous_srv(sr_state_get_current_srv());
1072 /* Nullify the current srv. */
1073 sr_state_set_current_srv(NULL);
1076 /* Set valid after time in the our state. */
1077 void
1078 sr_state_set_valid_after(time_t valid_after)
1080 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_VALID_AFTER,
1081 (void *) &valid_after, NULL);
1084 /* Return the phase we are currently in according to our state. */
1085 sr_phase_t
1086 sr_state_get_phase(void)
1088 void *ptr;
1089 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PHASE, NULL, &ptr);
1090 return *(sr_phase_t *) ptr;
1093 /* Return the previous SRV value from our state. Value CAN be NULL. */
1094 const sr_srv_t *
1095 sr_state_get_previous_srv(void)
1097 const sr_srv_t *srv;
1098 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PREVSRV, NULL,
1099 (void *) &srv);
1100 return srv;
1103 /* Set the current SRV value from our state. Value CAN be NULL. The srv
1104 * object ownership is transferred to the state object. */
1105 void
1106 sr_state_set_previous_srv(const sr_srv_t *srv)
1108 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_PREVSRV, (void *) srv,
1109 NULL);
1112 /* Return the current SRV value from our state. Value CAN be NULL. */
1113 const sr_srv_t *
1114 sr_state_get_current_srv(void)
1116 const sr_srv_t *srv;
1117 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_CURSRV, NULL,
1118 (void *) &srv);
1119 return srv;
1122 /* Set the current SRV value from our state. Value CAN be NULL. The srv
1123 * object ownership is transferred to the state object. */
1124 void
1125 sr_state_set_current_srv(const sr_srv_t *srv)
1127 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_CURSRV, (void *) srv,
1128 NULL);
1131 /* Clean all the SRVs in our state. */
1132 void
1133 sr_state_clean_srvs(void)
1135 /* Remove SRVs from state. They will be set to NULL as "empty". */
1136 state_del_previous_srv();
1137 state_del_current_srv();
1140 /* Return a pointer to the commits map from our state. CANNOT be NULL. */
1141 digestmap_t *
1142 sr_state_get_commits(void)
1144 digestmap_t *commits;
1145 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMITS,
1146 NULL, (void *) &commits);
1147 tor_assert(commits);
1148 return commits;
1151 /* Update the current SR state as needed for the upcoming voting round at
1152 * <b>valid_after</b>. */
1153 void
1154 sr_state_update(time_t valid_after)
1156 sr_phase_t next_phase;
1158 tor_assert(sr_state);
1160 /* Don't call this function twice in the same voting period. */
1161 if (valid_after <= sr_state->valid_after) {
1162 log_info(LD_DIR, "SR: Asked to update state twice. Ignoring.");
1163 return;
1166 /* Get phase of upcoming round. */
1167 next_phase = get_sr_protocol_phase(valid_after);
1169 /* If we are transitioning to a new protocol phase, prepare the stage. */
1170 if (is_phase_transition(next_phase)) {
1171 if (next_phase == SR_PHASE_COMMIT) {
1172 /* Going into commit phase means we are starting a new protocol run. */
1173 new_protocol_run(valid_after);
1175 /* Set the new phase for this round */
1176 sr_state->phase = next_phase;
1177 } else if (sr_state->phase == SR_PHASE_COMMIT &&
1178 digestmap_size(sr_state->commits) == 0) {
1179 /* We are _NOT_ in a transition phase so if we are in the commit phase
1180 * and have no commit, generate one. Chances are that we are booting up
1181 * so let's have a commit in our state for the next voting period. */
1182 sr_commit_t *our_commit =
1183 sr_generate_our_commit(valid_after, get_my_v3_authority_cert());
1184 if (our_commit) {
1185 /* Add our commitment to our state. In case we are unable to create one
1186 * (highly unlikely), we won't vote for this protocol run since our
1187 * commitment won't be in our state. */
1188 sr_state_add_commit(our_commit);
1192 sr_state_set_valid_after(valid_after);
1194 /* Count the current round */
1195 if (sr_state->phase == SR_PHASE_COMMIT) {
1196 /* invariant check: we've not entered reveal phase yet */
1197 tor_assert(sr_state->n_reveal_rounds == 0);
1198 sr_state->n_commit_rounds++;
1199 } else {
1200 sr_state->n_reveal_rounds++;
1203 { /* Debugging. */
1204 char tbuf[ISO_TIME_LEN + 1];
1205 format_iso_time(tbuf, valid_after);
1206 log_info(LD_DIR, "SR: State prepared for upcoming voting period (%s). "
1207 "Upcoming phase is %s (counters: %d commit & %d reveal rounds).",
1208 tbuf, get_phase_str(sr_state->phase),
1209 sr_state->n_commit_rounds, sr_state->n_reveal_rounds);
1213 /* Return commit object from the given authority digest <b>rsa_identity</b>.
1214 * Return NULL if not found. */
1215 sr_commit_t *
1216 sr_state_get_commit(const char *rsa_identity)
1218 sr_commit_t *commit;
1220 tor_assert(rsa_identity);
1222 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMIT,
1223 (void *) rsa_identity, (void *) &commit);
1224 return commit;
1227 /* Add <b>commit</b> to the permanent state. The commit object ownership is
1228 * transferred to the state so the caller MUST not free it. */
1229 void
1230 sr_state_add_commit(sr_commit_t *commit)
1232 tor_assert(commit);
1234 /* Put the commit to the global state. */
1235 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_COMMIT,
1236 (void *) commit, NULL);
1238 log_debug(LD_DIR, "SR: Commit from %s has been added to our state.",
1239 sr_commit_get_rsa_fpr(commit));
1242 /* Remove all commits from our state. */
1243 void
1244 sr_state_delete_commits(void)
1246 state_query(SR_STATE_ACTION_DEL_ALL, SR_STATE_OBJ_COMMIT, NULL, NULL);
1249 /* Copy the reveal information from <b>commit</b> into <b>saved_commit</b>.
1250 * This <b>saved_commit</b> MUST come from our current SR state. Once modified,
1251 * the disk state is updated. */
1252 void
1253 sr_state_copy_reveal_info(sr_commit_t *saved_commit, const sr_commit_t *commit)
1255 tor_assert(saved_commit);
1256 tor_assert(commit);
1258 saved_commit->reveal_ts = commit->reveal_ts;
1259 memcpy(saved_commit->random_number, commit->random_number,
1260 sizeof(saved_commit->random_number));
1262 strlcpy(saved_commit->encoded_reveal, commit->encoded_reveal,
1263 sizeof(saved_commit->encoded_reveal));
1264 state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
1265 log_debug(LD_DIR, "SR: Reveal value learned %s (for commit %s) from %s",
1266 saved_commit->encoded_reveal, saved_commit->encoded_commit,
1267 sr_commit_get_rsa_fpr(saved_commit));
1270 /* Set the fresh SRV flag from our state. This doesn't need to trigger a
1271 * disk state synchronization so we directly change the state. */
1272 void
1273 sr_state_set_fresh_srv(void)
1275 sr_state->is_srv_fresh = 1;
1278 /* Unset the fresh SRV flag from our state. This doesn't need to trigger a
1279 * disk state synchronization so we directly change the state. */
1280 void
1281 sr_state_unset_fresh_srv(void)
1283 sr_state->is_srv_fresh = 0;
1286 /* Return the value of the fresh SRV flag. */
1287 unsigned int
1288 sr_state_srv_is_fresh(void)
1290 return sr_state->is_srv_fresh;
1293 /* Cleanup and free our disk and memory state. */
1294 void
1295 sr_state_free_all(void)
1297 state_free(sr_state);
1298 disk_state_free(sr_disk_state);
1299 /* Nullify our global state. */
1300 sr_state = NULL;
1301 sr_disk_state = NULL;
1304 /* Save our current state in memory to disk. */
1305 void
1306 sr_state_save(void)
1308 /* Query a SAVE action on our current state so it's synced and saved. */
1309 state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
1312 /* Return 1 iff the state has been initialized that is it exists in memory.
1313 * Return 0 otherwise. */
1315 sr_state_is_initialized(void)
1317 return sr_state == NULL ? 0 : 1;
1320 /* Initialize the disk and memory state.
1322 * If save_to_disk is set to 1, the state is immediately saved to disk after
1323 * creation else it's not thus only kept in memory.
1324 * If read_from_disk is set to 1, we try to load the state from the disk and
1325 * if not found, a new state is created.
1327 * Return 0 on success else a negative value on error. */
1329 sr_state_init(int save_to_disk, int read_from_disk)
1331 int ret = -ENOENT;
1332 time_t now = time(NULL);
1334 /* We shouldn't have those assigned. */
1335 tor_assert(sr_disk_state == NULL);
1336 tor_assert(sr_state == NULL);
1338 /* First, try to load the state from disk. */
1339 if (read_from_disk) {
1340 ret = disk_state_load_from_disk();
1343 if (ret < 0) {
1344 switch (-ret) {
1345 case EINVAL:
1346 /* We have a state on disk but it contains something we couldn't parse
1347 * or an invalid entry in the state file. Let's remove it since it's
1348 * obviously unusable and replace it by an new fresh state below. */
1349 case ENOENT:
1351 /* No state on disk so allocate our states for the first time. */
1352 sr_state_t *new_state = state_new(default_fname, now);
1353 sr_disk_state_t *new_disk_state = disk_state_new(now);
1354 state_set(new_state);
1355 /* It's important to set our disk state pointer since the save call
1356 * below uses it to synchronized it with our memory state. */
1357 disk_state_set(new_disk_state);
1358 /* No entry, let's save our new state to disk. */
1359 if (save_to_disk && disk_state_save_to_disk() < 0) {
1360 goto error;
1362 break;
1364 default:
1365 /* Big problem. Not possible. */
1366 tor_assert(0);
1369 /* We have a state in memory, let's make sure it's updated for the current
1370 * and next voting round. */
1372 time_t valid_after = dirvote_get_next_valid_after_time();
1373 sr_state_update(valid_after);
1375 return 0;
1377 error:
1378 return -1;
1381 #ifdef TOR_UNIT_TESTS
1383 /* Set the current phase of the protocol. Used only by unit tests. */
1384 void
1385 set_sr_phase(sr_phase_t phase)
1387 tor_assert(sr_state);
1388 sr_state->phase = phase;
1391 /* Get the SR state. Used only by unit tests */
1392 sr_state_t *
1393 get_sr_state(void)
1395 return sr_state;
1398 #endif /* defined(TOR_UNIT_TESTS) */