Avoid crashing if we call num_usable_bridges() when bridges are not enabled
[tor/appveyor.git] / src / or / shared_random_state.c
blobae904cfda3f382889840e86318b8db6688e1088e
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 /* Free a state that was allocated with state_new(). */
278 static void
279 state_free(sr_state_t *state)
281 if (state == NULL) {
282 return;
284 tor_free(state->fname);
285 digestmap_free(state->commits, commit_free_);
286 tor_free(state->current_srv);
287 tor_free(state->previous_srv);
288 tor_free(state);
291 /* Allocate an sr_state_t object and returns it. If no <b>fname</b>, the
292 * default file name is used. This function does NOT initialize the state
293 * timestamp, phase or shared random value. NULL is never returned. */
294 static sr_state_t *
295 state_new(const char *fname, time_t now)
297 sr_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
298 /* If file name is not provided, use default. */
299 if (fname == NULL) {
300 fname = default_fname;
302 new_state->fname = tor_strdup(fname);
303 new_state->version = SR_PROTO_VERSION;
304 new_state->commits = digestmap_new();
305 new_state->phase = get_sr_protocol_phase(now);
306 new_state->valid_until = get_state_valid_until_time(now);
307 return new_state;
310 /* Set our global state pointer with the one given. */
311 static void
312 state_set(sr_state_t *state)
314 tor_assert(state);
315 if (sr_state != NULL) {
316 state_free(sr_state);
318 sr_state = state;
321 /* Free an allocated disk state. */
322 static void
323 disk_state_free(sr_disk_state_t *state)
325 if (state == NULL) {
326 return;
328 config_free(&state_format, state);
331 /* Allocate a new disk state, initialize it and return it. */
332 static sr_disk_state_t *
333 disk_state_new(time_t now)
335 sr_disk_state_t *new_state = tor_malloc_zero(sizeof(*new_state));
337 new_state->magic_ = SR_DISK_STATE_MAGIC;
338 new_state->Version = SR_PROTO_VERSION;
339 new_state->TorVersion = tor_strdup(get_version());
340 new_state->ValidUntil = get_state_valid_until_time(now);
341 new_state->ValidAfter = now;
343 /* Init config format. */
344 config_init(&state_format, new_state);
345 return new_state;
348 /* Set our global disk state with the given state. */
349 static void
350 disk_state_set(sr_disk_state_t *state)
352 tor_assert(state);
353 if (sr_disk_state != NULL) {
354 disk_state_free(sr_disk_state);
356 sr_disk_state = state;
359 /* Return -1 if the disk state is invalid (something in there that we can't or
360 * shouldn't use). Return 0 if everything checks out. */
361 static int
362 disk_state_validate(const sr_disk_state_t *state)
364 time_t now;
366 tor_assert(state);
368 /* Do we support the protocol version in the state or is it 0 meaning
369 * Version wasn't found in the state file or bad anyway ? */
370 if (state->Version == 0 || state->Version > SR_PROTO_VERSION) {
371 goto invalid;
374 /* If the valid until time is before now, we shouldn't use that state. */
375 now = time(NULL);
376 if (state->ValidUntil < now) {
377 log_info(LD_DIR, "SR: Disk state has expired. Ignoring it.");
378 goto invalid;
381 /* Make sure we don't have a valid after time that is earlier than a valid
382 * until time which would make things not work well. */
383 if (state->ValidAfter >= state->ValidUntil) {
384 log_info(LD_DIR, "SR: Disk state valid after/until times are invalid.");
385 goto invalid;
388 return 0;
390 invalid:
391 return -1;
394 /* Validate the disk state (NOP for now). */
395 static int
396 disk_state_validate_cb(void *old_state, void *state, void *default_state,
397 int from_setconf, char **msg)
399 /* We don't use these; only options do. */
400 (void) from_setconf;
401 (void) default_state;
402 (void) old_state;
404 /* This is called by config_dump which is just before we are about to
405 * write it to disk. At that point, our global memory state has been
406 * copied to the disk state so it's fair to assume it's trustable. */
407 (void) state;
408 (void) msg;
409 return 0;
412 /* Parse the Commit line(s) in the disk state and translate them to the
413 * the memory state. Return 0 on success else -1 on error. */
414 static int
415 disk_state_parse_commits(sr_state_t *state,
416 const sr_disk_state_t *disk_state)
418 config_line_t *line;
419 smartlist_t *args = NULL;
421 tor_assert(state);
422 tor_assert(disk_state);
424 for (line = disk_state->Commit; line; line = line->next) {
425 sr_commit_t *commit = NULL;
427 /* Extra safety. */
428 if (strcasecmp(line->key, dstate_commit_key) ||
429 line->value == NULL) {
430 /* Ignore any lines that are not commits. */
431 tor_fragile_assert();
432 continue;
434 args = smartlist_new();
435 smartlist_split_string(args, line->value, " ",
436 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
437 if (smartlist_len(args) < 3) {
438 log_warn(LD_BUG, "SR: Too few arguments in Commit Line: %s",
439 escaped(line->value));
440 goto error;
442 commit = sr_parse_commit(args);
443 if (commit == NULL) {
444 /* Ignore badly formed commit. It could also be a authority
445 * fingerprint that we don't know about so it shouldn't be used. */
446 continue;
448 /* We consider parseable commit from our disk state to be valid because
449 * they need to be in the first place to get in there. */
450 commit->valid = 1;
451 /* Add commit to our state pointer. */
452 commit_add_to_state(commit, state);
454 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
455 smartlist_free(args);
458 return 0;
460 error:
461 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
462 smartlist_free(args);
463 return -1;
466 /* Parse a share random value line from the disk state and save it to dst
467 * which is an allocated srv object. Return 0 on success else -1. */
468 static int
469 disk_state_parse_srv(const char *value, sr_srv_t *dst)
471 int ret = -1;
472 smartlist_t *args;
473 sr_srv_t *srv;
475 tor_assert(value);
476 tor_assert(dst);
478 args = smartlist_new();
479 smartlist_split_string(args, value, " ",
480 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
481 if (smartlist_len(args) < 2) {
482 log_warn(LD_BUG, "SR: Too few arguments in shared random value. "
483 "Line: %s", escaped(value));
484 goto error;
486 srv = sr_parse_srv(args);
487 if (srv == NULL) {
488 goto error;
490 dst->num_reveals = srv->num_reveals;
491 memcpy(dst->value, srv->value, sizeof(dst->value));
492 tor_free(srv);
493 ret = 0;
495 error:
496 SMARTLIST_FOREACH(args, char *, s, tor_free(s));
497 smartlist_free(args);
498 return ret;
501 /* Parse both SharedRandCurrentValue and SharedRandPreviousValue line from
502 * the state. Return 0 on success else -1. */
503 static int
504 disk_state_parse_sr_values(sr_state_t *state,
505 const sr_disk_state_t *disk_state)
507 /* Only one value per type (current or previous) is allowed so we keep
508 * track of it with these flag. */
509 unsigned int seen_previous = 0, seen_current = 0;
510 config_line_t *line;
511 sr_srv_t *srv = NULL;
513 tor_assert(state);
514 tor_assert(disk_state);
516 for (line = disk_state->SharedRandValues; line; line = line->next) {
517 if (line->value == NULL) {
518 continue;
520 srv = tor_malloc_zero(sizeof(*srv));
521 if (disk_state_parse_srv(line->value, srv) < 0) {
522 log_warn(LD_BUG, "SR: Broken current SRV line in state %s",
523 escaped(line->value));
524 goto bad;
526 if (!strcasecmp(line->key, dstate_prev_srv_key)) {
527 if (seen_previous) {
528 log_warn(LD_DIR, "SR: Second previous SRV value seen. Bad state");
529 goto bad;
531 state->previous_srv = srv;
532 seen_previous = 1;
533 } else if (!strcasecmp(line->key, dstate_cur_srv_key)) {
534 if (seen_current) {
535 log_warn(LD_DIR, "SR: Second current SRV value seen. Bad state");
536 goto bad;
538 state->current_srv = srv;
539 seen_current = 1;
540 } else {
541 /* Unknown key. Ignoring. */
542 tor_free(srv);
546 return 0;
547 bad:
548 tor_free(srv);
549 return -1;
552 /* Parse the given disk state and set a newly allocated state. On success,
553 * return that state else NULL. */
554 static sr_state_t *
555 disk_state_parse(const sr_disk_state_t *new_disk_state)
557 sr_state_t *new_state = state_new(default_fname, time(NULL));
559 tor_assert(new_disk_state);
561 new_state->version = new_disk_state->Version;
562 new_state->valid_until = new_disk_state->ValidUntil;
563 new_state->valid_after = new_disk_state->ValidAfter;
565 /* Set our current phase according to the valid-after time in our disk
566 * state. The disk state we are parsing contains everything for the phase
567 * starting at valid_after so make sure our phase reflects that. */
568 new_state->phase = get_sr_protocol_phase(new_state->valid_after);
570 /* Parse the shared random values. */
571 if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
572 goto error;
574 /* Parse the commits. */
575 if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
576 goto error;
578 /* Great! This new state contains everything we had on disk. */
579 return new_state;
581 error:
582 state_free(new_state);
583 return NULL;
586 /* From a valid commit object and an allocated config line, set the line's
587 * value to the state string representation of a commit. */
588 static void
589 disk_state_put_commit_line(const sr_commit_t *commit, config_line_t *line)
591 char *reveal_str = NULL;
593 tor_assert(commit);
594 tor_assert(line);
596 if (!tor_mem_is_zero(commit->encoded_reveal,
597 sizeof(commit->encoded_reveal))) {
598 /* Add extra whitespace so we can format the line correctly. */
599 tor_asprintf(&reveal_str, " %s", commit->encoded_reveal);
601 tor_asprintf(&line->value, "%u %s %s %s%s",
602 SR_PROTO_VERSION,
603 crypto_digest_algorithm_get_name(commit->alg),
604 sr_commit_get_rsa_fpr(commit),
605 commit->encoded_commit,
606 reveal_str != NULL ? reveal_str : "");
607 if (reveal_str != NULL) {
608 memwipe(reveal_str, 0, strlen(reveal_str));
609 tor_free(reveal_str);
613 /* From a valid srv object and an allocated config line, set the line's
614 * value to the state string representation of a shared random value. */
615 static void
616 disk_state_put_srv_line(const sr_srv_t *srv, config_line_t *line)
618 char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
620 tor_assert(line);
622 /* No SRV value thus don't add the line. This is possible since we might
623 * not have a current or previous SRV value in our state. */
624 if (srv == NULL) {
625 return;
627 sr_srv_encode(encoded, sizeof(encoded), srv);
628 tor_asprintf(&line->value, "%" PRIu64 " %s", srv->num_reveals, encoded);
631 /* Reset disk state that is free allocated memory and zeroed the object. */
632 static void
633 disk_state_reset(void)
635 /* Free allocated memory */
636 config_free_lines(sr_disk_state->Commit);
637 config_free_lines(sr_disk_state->SharedRandValues);
638 config_free_lines(sr_disk_state->ExtraLines);
639 tor_free(sr_disk_state->TorVersion);
641 /* Clean up the struct */
642 memset(sr_disk_state, 0, sizeof(*sr_disk_state));
644 /* Reset it with useful data */
645 sr_disk_state->magic_ = SR_DISK_STATE_MAGIC;
646 sr_disk_state->TorVersion = tor_strdup(get_version());
649 /* Update our disk state based on our global SR state. */
650 static void
651 disk_state_update(void)
653 config_line_t **next, *line;
655 tor_assert(sr_disk_state);
656 tor_assert(sr_state);
658 /* Reset current disk state. */
659 disk_state_reset();
661 /* First, update elements that we don't need to do a construction. */
662 sr_disk_state->Version = sr_state->version;
663 sr_disk_state->ValidUntil = sr_state->valid_until;
664 sr_disk_state->ValidAfter = sr_state->valid_after;
666 /* Shared random values. */
667 next = &sr_disk_state->SharedRandValues;
668 if (sr_state->previous_srv != NULL) {
669 *next = line = tor_malloc_zero(sizeof(config_line_t));
670 line->key = tor_strdup(dstate_prev_srv_key);
671 disk_state_put_srv_line(sr_state->previous_srv, line);
672 /* Go to the next shared random value. */
673 next = &(line->next);
675 if (sr_state->current_srv != NULL) {
676 *next = line = tor_malloc_zero(sizeof(*line));
677 line->key = tor_strdup(dstate_cur_srv_key);
678 disk_state_put_srv_line(sr_state->current_srv, line);
681 /* Parse the commits and construct config line(s). */
682 next = &sr_disk_state->Commit;
683 DIGESTMAP_FOREACH(sr_state->commits, key, sr_commit_t *, commit) {
684 *next = line = tor_malloc_zero(sizeof(*line));
685 line->key = tor_strdup(dstate_commit_key);
686 disk_state_put_commit_line(commit, line);
687 next = &(line->next);
688 } DIGESTMAP_FOREACH_END;
691 /* Load state from disk and put it into our disk state. If the state passes
692 * validation, our global state will be updated with it. Return 0 on
693 * success. On error, -EINVAL is returned if the state on disk did contained
694 * something malformed or is unreadable. -ENOENT is returned indicating that
695 * the state file is either empty of non existing. */
696 static int
697 disk_state_load_from_disk(void)
699 int ret;
700 char *fname;
702 fname = get_datadir_fname(default_fname);
703 ret = disk_state_load_from_disk_impl(fname);
704 tor_free(fname);
706 return ret;
709 /* Helper for disk_state_load_from_disk(). */
710 STATIC int
711 disk_state_load_from_disk_impl(const char *fname)
713 int ret;
714 char *content = NULL;
715 sr_state_t *parsed_state = NULL;
716 sr_disk_state_t *disk_state = NULL;
718 /* Read content of file so we can parse it. */
719 if ((content = read_file_to_str(fname, 0, NULL)) == NULL) {
720 log_warn(LD_FS, "SR: Unable to read SR state file %s",
721 escaped(fname));
722 ret = -errno;
723 goto error;
727 config_line_t *lines = NULL;
728 char *errmsg = NULL;
730 /* Every error in this code path will return EINVAL. */
731 ret = -EINVAL;
732 if (config_get_lines(content, &lines, 0) < 0) {
733 config_free_lines(lines);
734 goto error;
737 disk_state = disk_state_new(time(NULL));
738 config_assign(&state_format, disk_state, lines, 0, &errmsg);
739 config_free_lines(lines);
740 if (errmsg) {
741 log_warn(LD_DIR, "SR: Reading state error: %s", errmsg);
742 tor_free(errmsg);
743 goto error;
747 /* So far so good, we've loaded our state file into our disk state. Let's
748 * validate it and then parse it. */
749 if (disk_state_validate(disk_state) < 0) {
750 ret = -EINVAL;
751 goto error;
754 parsed_state = disk_state_parse(disk_state);
755 if (parsed_state == NULL) {
756 ret = -EINVAL;
757 goto error;
759 state_set(parsed_state);
760 disk_state_set(disk_state);
761 tor_free(content);
762 log_info(LD_DIR, "SR: State loaded successfully from file %s", fname);
763 return 0;
765 error:
766 disk_state_free(disk_state);
767 tor_free(content);
768 return ret;
771 /* Save the disk state to disk but before that update it from the current
772 * state so we always have the latest. Return 0 on success else -1. */
773 static int
774 disk_state_save_to_disk(void)
776 int ret;
777 char *state, *content = NULL, *fname = NULL;
778 char tbuf[ISO_TIME_LEN + 1];
779 time_t now = time(NULL);
781 /* If we didn't have the opportunity to setup an internal disk state,
782 * don't bother saving something to disk. */
783 if (sr_disk_state == NULL) {
784 ret = 0;
785 goto done;
788 /* Make sure that our disk state is up to date with our memory state
789 * before saving it to disk. */
790 disk_state_update();
791 state = config_dump(&state_format, NULL, sr_disk_state, 0, 0);
792 format_local_iso_time(tbuf, now);
793 tor_asprintf(&content,
794 "# Tor shared random state file last generated on %s "
795 "local time\n"
796 "# Other times below are in UTC\n"
797 "# Please *do not* edit this file.\n\n%s",
798 tbuf, state);
799 tor_free(state);
800 fname = get_datadir_fname(default_fname);
801 if (write_str_to_file(fname, content, 0) < 0) {
802 log_warn(LD_FS, "SR: Unable to write SR state to file %s", fname);
803 ret = -1;
804 goto done;
806 ret = 0;
807 log_debug(LD_DIR, "SR: Saved state to file %s", fname);
809 done:
810 tor_free(fname);
811 tor_free(content);
812 return ret;
815 /* Reset our state to prepare for a new protocol run. Once this returns, all
816 * commits in the state will be removed and freed. */
817 STATIC void
818 reset_state_for_new_protocol_run(time_t valid_after)
820 tor_assert(sr_state);
822 /* Keep counters in track */
823 sr_state->n_reveal_rounds = 0;
824 sr_state->n_commit_rounds = 0;
825 sr_state->n_protocol_runs++;
827 /* Reset valid-until */
828 sr_state->valid_until = get_state_valid_until_time(valid_after);
829 sr_state->valid_after = valid_after;
831 /* We are in a new protocol run so cleanup commits. */
832 sr_state_delete_commits();
835 /* This is the first round of the new protocol run starting at
836 * <b>valid_after</b>. Do the necessary housekeeping. */
837 STATIC void
838 new_protocol_run(time_t valid_after)
840 sr_commit_t *our_commitment = NULL;
842 /* Only compute the srv at the end of the reveal phase. */
843 if (sr_state->phase == SR_PHASE_REVEAL) {
844 /* We are about to compute a new shared random value that will be set in
845 * our state as the current value so rotate values. */
846 state_rotate_srv();
847 /* Compute the shared randomness value of the day. */
848 sr_compute_srv();
851 /* Prepare for the new protocol run by reseting the state */
852 reset_state_for_new_protocol_run(valid_after);
854 /* Do some logging */
855 log_info(LD_DIR, "SR: Protocol run #%" PRIu64 " starting!",
856 sr_state->n_protocol_runs);
858 /* Generate fresh commitments for this protocol run */
859 our_commitment = sr_generate_our_commit(valid_after,
860 get_my_v3_authority_cert());
861 if (our_commitment) {
862 /* Add our commitment to our state. In case we are unable to create one
863 * (highly unlikely), we won't vote for this protocol run since our
864 * commitment won't be in our state. */
865 sr_state_add_commit(our_commitment);
869 /* Return 1 iff the <b>next_phase</b> is a phase transition from the current
870 * phase that is it's different. */
871 STATIC int
872 is_phase_transition(sr_phase_t next_phase)
874 return sr_state->phase != next_phase;
877 /* Helper function: return a commit using the RSA fingerprint of the
878 * authority or NULL if no such commit is known. */
879 static sr_commit_t *
880 state_query_get_commit(const char *rsa_fpr)
882 tor_assert(rsa_fpr);
883 return digestmap_get(sr_state->commits, rsa_fpr);
886 /* Helper function: This handles the GET state action using an
887 * <b>obj_type</b> and <b>data</b> needed for the action. */
888 static void *
889 state_query_get_(sr_state_object_t obj_type, const void *data)
891 void *obj = NULL;
893 switch (obj_type) {
894 case SR_STATE_OBJ_COMMIT:
896 obj = state_query_get_commit(data);
897 break;
899 case SR_STATE_OBJ_COMMITS:
900 obj = sr_state->commits;
901 break;
902 case SR_STATE_OBJ_CURSRV:
903 obj = sr_state->current_srv;
904 break;
905 case SR_STATE_OBJ_PREVSRV:
906 obj = sr_state->previous_srv;
907 break;
908 case SR_STATE_OBJ_PHASE:
909 obj = &sr_state->phase;
910 break;
911 case SR_STATE_OBJ_VALID_AFTER:
912 default:
913 tor_assert(0);
915 return obj;
918 /* Helper function: This handles the PUT state action using an
919 * <b>obj_type</b> and <b>data</b> needed for the action. */
920 static void
921 state_query_put_(sr_state_object_t obj_type, void *data)
923 switch (obj_type) {
924 case SR_STATE_OBJ_COMMIT:
926 sr_commit_t *commit = data;
927 tor_assert(commit);
928 commit_add_to_state(commit, sr_state);
929 break;
931 case SR_STATE_OBJ_CURSRV:
932 sr_state->current_srv = (sr_srv_t *) data;
933 break;
934 case SR_STATE_OBJ_PREVSRV:
935 sr_state->previous_srv = (sr_srv_t *) data;
936 break;
937 case SR_STATE_OBJ_VALID_AFTER:
938 sr_state->valid_after = *((time_t *) data);
939 break;
940 /* It's not allowed to change the phase nor the full commitments map from
941 * the state. The phase is decided during a strict process post voting and
942 * the commits should be put individually. */
943 case SR_STATE_OBJ_PHASE:
944 case SR_STATE_OBJ_COMMITS:
945 default:
946 tor_assert(0);
950 /* Helper function: This handles the DEL_ALL state action using an
951 * <b>obj_type</b> and <b>data</b> needed for the action. */
952 static void
953 state_query_del_all_(sr_state_object_t obj_type)
955 switch (obj_type) {
956 case SR_STATE_OBJ_COMMIT:
958 /* We are in a new protocol run so cleanup commitments. */
959 DIGESTMAP_FOREACH_MODIFY(sr_state->commits, key, sr_commit_t *, c) {
960 sr_commit_free(c);
961 MAP_DEL_CURRENT(key);
962 } DIGESTMAP_FOREACH_END;
963 break;
965 /* The following object are _NOT_ suppose to be removed. */
966 case SR_STATE_OBJ_CURSRV:
967 case SR_STATE_OBJ_PREVSRV:
968 case SR_STATE_OBJ_PHASE:
969 case SR_STATE_OBJ_COMMITS:
970 case SR_STATE_OBJ_VALID_AFTER:
971 default:
972 tor_assert(0);
976 /* Helper function: This handles the DEL state action using an
977 * <b>obj_type</b> and <b>data</b> needed for the action. */
978 static void
979 state_query_del_(sr_state_object_t obj_type, void *data)
981 (void) data;
983 switch (obj_type) {
984 case SR_STATE_OBJ_PREVSRV:
985 tor_free(sr_state->previous_srv);
986 break;
987 case SR_STATE_OBJ_CURSRV:
988 tor_free(sr_state->current_srv);
989 break;
990 case SR_STATE_OBJ_COMMIT:
991 case SR_STATE_OBJ_COMMITS:
992 case SR_STATE_OBJ_PHASE:
993 case SR_STATE_OBJ_VALID_AFTER:
994 default:
995 tor_assert(0);
999 /* Query state using an <b>action</b> for an object type <b>obj_type</b>.
1000 * The <b>data</b> pointer needs to point to an object that the action needs
1001 * to use and if anything is required to be returned, it is stored in
1002 * <b>out</b>.
1004 * This mechanism exists so we have one single point where we synchronized
1005 * our memory state with our disk state for every actions that changes it.
1006 * We then trigger a write on disk immediately.
1008 * This should be the only entry point to our memory state. It's used by all
1009 * our state accessors and should be in the future. */
1010 static void
1011 state_query(sr_state_action_t action, sr_state_object_t obj_type,
1012 void *data, void **out)
1014 switch (action) {
1015 case SR_STATE_ACTION_GET:
1016 *out = state_query_get_(obj_type, data);
1017 break;
1018 case SR_STATE_ACTION_PUT:
1019 state_query_put_(obj_type, data);
1020 break;
1021 case SR_STATE_ACTION_DEL:
1022 state_query_del_(obj_type, data);
1023 break;
1024 case SR_STATE_ACTION_DEL_ALL:
1025 state_query_del_all_(obj_type);
1026 break;
1027 case SR_STATE_ACTION_SAVE:
1028 /* Only trigger a disk state save. */
1029 break;
1030 default:
1031 tor_assert(0);
1034 /* If the action actually changes the state, immediately save it to disk.
1035 * The following will sync the state -> disk state and then save it. */
1036 if (action != SR_STATE_ACTION_GET) {
1037 disk_state_save_to_disk();
1041 /* Delete the current SRV value from the state freeing it and the value is set
1042 * to NULL meaning empty. */
1043 static void
1044 state_del_current_srv(void)
1046 state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_CURSRV, NULL, NULL);
1049 /* Delete the previous SRV value from the state freeing it and the value is
1050 * set to NULL meaning empty. */
1051 static void
1052 state_del_previous_srv(void)
1054 state_query(SR_STATE_ACTION_DEL, SR_STATE_OBJ_PREVSRV, NULL, NULL);
1057 /* Rotate SRV value by freeing the previous value, assigning the current
1058 * value to the previous one and nullifying the current one. */
1059 STATIC void
1060 state_rotate_srv(void)
1062 /* First delete previous SRV from the state. Object will be freed. */
1063 state_del_previous_srv();
1064 /* Set previous SRV with the current one. */
1065 sr_state_set_previous_srv(sr_state_get_current_srv());
1066 /* Nullify the current srv. */
1067 sr_state_set_current_srv(NULL);
1070 /* Set valid after time in the our state. */
1071 void
1072 sr_state_set_valid_after(time_t valid_after)
1074 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_VALID_AFTER,
1075 (void *) &valid_after, NULL);
1078 /* Return the phase we are currently in according to our state. */
1079 sr_phase_t
1080 sr_state_get_phase(void)
1082 void *ptr;
1083 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PHASE, NULL, &ptr);
1084 return *(sr_phase_t *) ptr;
1087 /* Return the previous SRV value from our state. Value CAN be NULL. */
1088 const sr_srv_t *
1089 sr_state_get_previous_srv(void)
1091 const sr_srv_t *srv;
1092 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_PREVSRV, NULL,
1093 (void *) &srv);
1094 return srv;
1097 /* Set the current SRV value from our state. Value CAN be NULL. The srv
1098 * object ownership is transfered to the state object. */
1099 void
1100 sr_state_set_previous_srv(const sr_srv_t *srv)
1102 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_PREVSRV, (void *) srv,
1103 NULL);
1106 /* Return the current SRV value from our state. Value CAN be NULL. */
1107 const sr_srv_t *
1108 sr_state_get_current_srv(void)
1110 const sr_srv_t *srv;
1111 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_CURSRV, NULL,
1112 (void *) &srv);
1113 return srv;
1116 /* Set the current SRV value from our state. Value CAN be NULL. The srv
1117 * object ownership is transfered to the state object. */
1118 void
1119 sr_state_set_current_srv(const sr_srv_t *srv)
1121 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_CURSRV, (void *) srv,
1122 NULL);
1125 /* Clean all the SRVs in our state. */
1126 void
1127 sr_state_clean_srvs(void)
1129 /* Remove SRVs from state. They will be set to NULL as "empty". */
1130 state_del_previous_srv();
1131 state_del_current_srv();
1134 /* Return a pointer to the commits map from our state. CANNOT be NULL. */
1135 digestmap_t *
1136 sr_state_get_commits(void)
1138 digestmap_t *commits;
1139 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMITS,
1140 NULL, (void *) &commits);
1141 tor_assert(commits);
1142 return commits;
1145 /* Update the current SR state as needed for the upcoming voting round at
1146 * <b>valid_after</b>. */
1147 void
1148 sr_state_update(time_t valid_after)
1150 sr_phase_t next_phase;
1152 tor_assert(sr_state);
1154 /* Don't call this function twice in the same voting period. */
1155 if (valid_after <= sr_state->valid_after) {
1156 log_info(LD_DIR, "SR: Asked to update state twice. Ignoring.");
1157 return;
1160 /* Get phase of upcoming round. */
1161 next_phase = get_sr_protocol_phase(valid_after);
1163 /* If we are transitioning to a new protocol phase, prepare the stage. */
1164 if (is_phase_transition(next_phase)) {
1165 if (next_phase == SR_PHASE_COMMIT) {
1166 /* Going into commit phase means we are starting a new protocol run. */
1167 new_protocol_run(valid_after);
1169 /* Set the new phase for this round */
1170 sr_state->phase = next_phase;
1171 } else if (sr_state->phase == SR_PHASE_COMMIT &&
1172 digestmap_size(sr_state->commits) == 0) {
1173 /* We are _NOT_ in a transition phase so if we are in the commit phase
1174 * and have no commit, generate one. Chances are that we are booting up
1175 * so let's have a commit in our state for the next voting period. */
1176 sr_commit_t *our_commit =
1177 sr_generate_our_commit(valid_after, get_my_v3_authority_cert());
1178 if (our_commit) {
1179 /* Add our commitment to our state. In case we are unable to create one
1180 * (highly unlikely), we won't vote for this protocol run since our
1181 * commitment won't be in our state. */
1182 sr_state_add_commit(our_commit);
1186 sr_state_set_valid_after(valid_after);
1188 /* Count the current round */
1189 if (sr_state->phase == SR_PHASE_COMMIT) {
1190 /* invariant check: we've not entered reveal phase yet */
1191 tor_assert(sr_state->n_reveal_rounds == 0);
1192 sr_state->n_commit_rounds++;
1193 } else {
1194 sr_state->n_reveal_rounds++;
1197 { /* Debugging. */
1198 char tbuf[ISO_TIME_LEN + 1];
1199 format_iso_time(tbuf, valid_after);
1200 log_info(LD_DIR, "SR: State prepared for upcoming voting period (%s). "
1201 "Upcoming phase is %s (counters: %d commit & %d reveal rounds).",
1202 tbuf, get_phase_str(sr_state->phase),
1203 sr_state->n_commit_rounds, sr_state->n_reveal_rounds);
1207 /* Return commit object from the given authority digest <b>rsa_identity</b>.
1208 * Return NULL if not found. */
1209 sr_commit_t *
1210 sr_state_get_commit(const char *rsa_identity)
1212 sr_commit_t *commit;
1214 tor_assert(rsa_identity);
1216 state_query(SR_STATE_ACTION_GET, SR_STATE_OBJ_COMMIT,
1217 (void *) rsa_identity, (void *) &commit);
1218 return commit;
1221 /* Add <b>commit</b> to the permanent state. The commit object ownership is
1222 * transfered to the state so the caller MUST not free it. */
1223 void
1224 sr_state_add_commit(sr_commit_t *commit)
1226 tor_assert(commit);
1228 /* Put the commit to the global state. */
1229 state_query(SR_STATE_ACTION_PUT, SR_STATE_OBJ_COMMIT,
1230 (void *) commit, NULL);
1232 log_debug(LD_DIR, "SR: Commit from %s has been added to our state.",
1233 sr_commit_get_rsa_fpr(commit));
1236 /* Remove all commits from our state. */
1237 void
1238 sr_state_delete_commits(void)
1240 state_query(SR_STATE_ACTION_DEL_ALL, SR_STATE_OBJ_COMMIT, NULL, NULL);
1243 /* Copy the reveal information from <b>commit</b> into <b>saved_commit</b>.
1244 * This <b>saved_commit</b> MUST come from our current SR state. Once modified,
1245 * the disk state is updated. */
1246 void
1247 sr_state_copy_reveal_info(sr_commit_t *saved_commit, const sr_commit_t *commit)
1249 tor_assert(saved_commit);
1250 tor_assert(commit);
1252 saved_commit->reveal_ts = commit->reveal_ts;
1253 memcpy(saved_commit->random_number, commit->random_number,
1254 sizeof(saved_commit->random_number));
1256 strlcpy(saved_commit->encoded_reveal, commit->encoded_reveal,
1257 sizeof(saved_commit->encoded_reveal));
1258 state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
1259 log_debug(LD_DIR, "SR: Reveal value learned %s (for commit %s) from %s",
1260 saved_commit->encoded_reveal, saved_commit->encoded_commit,
1261 sr_commit_get_rsa_fpr(saved_commit));
1264 /* Set the fresh SRV flag from our state. This doesn't need to trigger a
1265 * disk state synchronization so we directly change the state. */
1266 void
1267 sr_state_set_fresh_srv(void)
1269 sr_state->is_srv_fresh = 1;
1272 /* Unset the fresh SRV flag from our state. This doesn't need to trigger a
1273 * disk state synchronization so we directly change the state. */
1274 void
1275 sr_state_unset_fresh_srv(void)
1277 sr_state->is_srv_fresh = 0;
1280 /* Return the value of the fresh SRV flag. */
1281 unsigned int
1282 sr_state_srv_is_fresh(void)
1284 return sr_state->is_srv_fresh;
1287 /* Cleanup and free our disk and memory state. */
1288 void
1289 sr_state_free(void)
1291 state_free(sr_state);
1292 disk_state_free(sr_disk_state);
1293 /* Nullify our global state. */
1294 sr_state = NULL;
1295 sr_disk_state = NULL;
1298 /* Save our current state in memory to disk. */
1299 void
1300 sr_state_save(void)
1302 /* Query a SAVE action on our current state so it's synced and saved. */
1303 state_query(SR_STATE_ACTION_SAVE, 0, NULL, NULL);
1306 /* Return 1 iff the state has been initialized that is it exists in memory.
1307 * Return 0 otherwise. */
1309 sr_state_is_initialized(void)
1311 return sr_state == NULL ? 0 : 1;
1314 /* Initialize the disk and memory state.
1316 * If save_to_disk is set to 1, the state is immediately saved to disk after
1317 * creation else it's not thus only kept in memory.
1318 * If read_from_disk is set to 1, we try to load the state from the disk and
1319 * if not found, a new state is created.
1321 * Return 0 on success else a negative value on error. */
1323 sr_state_init(int save_to_disk, int read_from_disk)
1325 int ret = -ENOENT;
1326 time_t now = time(NULL);
1328 /* We shouldn't have those assigned. */
1329 tor_assert(sr_disk_state == NULL);
1330 tor_assert(sr_state == NULL);
1332 /* First, try to load the state from disk. */
1333 if (read_from_disk) {
1334 ret = disk_state_load_from_disk();
1337 if (ret < 0) {
1338 switch (-ret) {
1339 case EINVAL:
1340 /* We have a state on disk but it contains something we couldn't parse
1341 * or an invalid entry in the state file. Let's remove it since it's
1342 * obviously unusable and replace it by an new fresh state below. */
1343 case ENOENT:
1345 /* No state on disk so allocate our states for the first time. */
1346 sr_state_t *new_state = state_new(default_fname, now);
1347 sr_disk_state_t *new_disk_state = disk_state_new(now);
1348 state_set(new_state);
1349 /* It's important to set our disk state pointer since the save call
1350 * below uses it to synchronized it with our memory state. */
1351 disk_state_set(new_disk_state);
1352 /* No entry, let's save our new state to disk. */
1353 if (save_to_disk && disk_state_save_to_disk() < 0) {
1354 goto error;
1356 break;
1358 default:
1359 /* Big problem. Not possible. */
1360 tor_assert(0);
1363 /* We have a state in memory, let's make sure it's updated for the current
1364 * and next voting round. */
1366 time_t valid_after = dirvote_get_next_valid_after_time();
1367 sr_state_update(valid_after);
1369 return 0;
1371 error:
1372 return -1;
1375 #ifdef TOR_UNIT_TESTS
1377 /* Set the current phase of the protocol. Used only by unit tests. */
1378 void
1379 set_sr_phase(sr_phase_t phase)
1381 tor_assert(sr_state);
1382 sr_state->phase = phase;
1385 /* Get the SR state. Used only by unit tests */
1386 sr_state_t *
1387 get_sr_state(void)
1389 return sr_state;
1392 #endif /* defined(TOR_UNIT_TESTS) */