dirvote.c 114 KB
Newer Older
1
2
/* Copyright (c) 2001-2004, Roger Dingledine.
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Karsten Loesing's avatar
Karsten Loesing committed
3
 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4
5
/* See LICENSE for licensing information */

6
#define DIRVOTE_PRIVATE
7
8
9
10
#include "or.h"

/**
 * \file dirvote.c
11
 * \brief Functions to compute directory consensus, and schedule voting.
12
13
 **/

14
15
16
/** A consensus that we have built and are appending signatures to.  Once it's
 * time to publish it, it will become an active consensus if it accumulates
 * enough signatures. */
17
18
19
20
21
22
23
typedef struct pending_consensus_t {
  /** The body of the consensus that we're currently building.  Once we
   * have it built, it goes into dirserv.c */
  char *body;
  /** The parsed in-progress consensus document. */
  networkstatus_t *consensus;
} pending_consensus_t;
24
25

static int dirvote_add_signatures_to_all_pending_consensuses(
26
27
                       const char *detached_signatures_body,
                       const char **msg_out);
28
29
30
31
static int dirvote_add_signatures_to_pending_consensus(
                       pending_consensus_t *pc,
                       ns_detached_signatures_t *sigs,
                       const char **msg_out);
32
static char *list_v3_auth_ids(void);
33
34
static void dirvote_fetch_missing_votes(void);
static void dirvote_fetch_missing_signatures(void);
35
static int dirvote_perform_vote(void);
36
static void dirvote_clear_votes(int all_votes);
37
static int dirvote_compute_consensuses(void);
38
static int dirvote_publish_consensus(void);
39
static char *make_consensus_method_list(int low, int high, const char *sep);
40
41

/** The highest consensus method that we currently support. */
42
#define MAX_SUPPORTED_CONSENSUS_METHOD 9
43

Mike Perry's avatar
Mike Perry committed
44
45
46
47
48
49
50
/** Lowest consensus method that contains a 'directory-footer' marker */
#define MIN_METHOD_FOR_FOOTER 9

/** Lowest consensus method that contains bandwidth weights */
#define MIN_METHOD_FOR_BW_WEIGHTS 9

/** Lowest consensus method that contains consensus params */
51
#define MIN_METHOD_FOR_PARAMS 7
52

53
54
55
/** Lowest consensus method that generates microdescriptors */
#define MIN_METHOD_FOR_MICRODESC 8

56
/* =====
57
58
 * Voting
 * =====*/
59

60
61
62
/* Overestimated. */
#define MICRODESC_LINE_LEN 80

Roger Dingledine's avatar
emo teh    
Roger Dingledine committed
63
/** Return a new string containing the string representation of the vote in
64
65
66
67
 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
 * For v3 authorities. */
char *
format_networkstatus_vote(crypto_pk_env_t *private_signing_key,
68
                          networkstatus_t *v3_ns)
69
{
70
71
72
73
74
75
76
77
78
79
80
  size_t len;
  char *status = NULL;
  const char *client_versions = NULL, *server_versions = NULL;
  char *outp, *endp;
  char fingerprint[FINGERPRINT_LEN+1];
  char ipaddr[INET_NTOA_BUF_LEN];
  char digest[DIGEST_LEN];
  struct in_addr in;
  uint32_t addr;
  routerlist_t *rl = router_get_routerlist();
  char *version_lines = NULL;
81
  int r;
82
83
84
  networkstatus_voter_info_t *voter;

  tor_assert(private_signing_key);
85
  tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

  voter = smartlist_get(v3_ns->voters, 0);

  addr = voter->addr;
  in.s_addr = htonl(addr);
  tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));

  base16_encode(fingerprint, sizeof(fingerprint),
                v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
  client_versions = v3_ns->client_versions;
  server_versions = v3_ns->server_versions;

  if (client_versions || server_versions) {
    size_t v_len = 64;
    char *cp;
    if (client_versions)
      v_len += strlen(client_versions);
103
    if (server_versions)
104
105
106
107
      v_len += strlen(server_versions);
    version_lines = tor_malloc(v_len);
    cp = version_lines;
    if (client_versions) {
108
      r = tor_snprintf(cp, v_len-(cp-version_lines),
109
                   "client-versions %s\n", client_versions);
110
111
112
113
      if (r < 0) {
        log_err(LD_BUG, "Insufficient memory for client-versions line");
        tor_assert(0);
      }
114
115
      cp += strlen(cp);
    }
116
117
    if (server_versions) {
      r = tor_snprintf(cp, v_len-(cp-version_lines),
118
                   "server-versions %s\n", server_versions);
119
120
121
122
123
      if (r < 0) {
        log_err(LD_BUG, "Insufficient memory for server-versions line");
        tor_assert(0);
      }
    }
124
125
  } else {
    version_lines = tor_strdup("");
126
  }
127
128
129

  len = 8192;
  len += strlen(version_lines);
130
  len += (RS_ENTRY_LEN+MICRODESC_LINE_LEN)*smartlist_len(rl->routers);
131
  len += strlen("\ndirectory-footer\n");
132
133
134
135
136
137
138
139
140
  len += v3_ns->cert->cache_info.signed_descriptor_len;

  status = tor_malloc(len);
  {
    char published[ISO_TIME_LEN+1];
    char va[ISO_TIME_LEN+1];
    char fu[ISO_TIME_LEN+1];
    char vu[ISO_TIME_LEN+1];
    char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
141
    char *params;
142
    authority_cert_t *cert = v3_ns->cert;
143
    char *methods =
144
      make_consensus_method_list(1, MAX_SUPPORTED_CONSENSUS_METHOD, " ");
145
146
147
148
149
    format_iso_time(published, v3_ns->published);
    format_iso_time(va, v3_ns->valid_after);
    format_iso_time(fu, v3_ns->fresh_until);
    format_iso_time(vu, v3_ns->valid_until);

150
151
152
153
154
    if (v3_ns->net_params)
      params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
    else
      params = tor_strdup("");

155
    tor_assert(cert);
156
    r = tor_snprintf(status, len,
157
                 "network-status-version 3\n"
158
                 "vote-status %s\n"
159
                 "consensus-methods %s\n"
160
161
162
163
164
165
166
                 "published %s\n"
                 "valid-after %s\n"
                 "fresh-until %s\n"
                 "valid-until %s\n"
                 "voting-delay %d %d\n"
                 "%s" /* versions */
                 "known-flags %s\n"
167
                 "params %s\n"
168
169
                 "dir-source %s %s %s %s %d %d\n"
                 "contact %s\n",
170
                 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
171
                 methods,
172
173
174
175
                 published, va, fu, vu,
                 v3_ns->vote_seconds, v3_ns->dist_seconds,
                 version_lines,
                 flags,
176
                 params,
177
                 voter->nickname, fingerprint, voter->address,
178
                 ipaddr, voter->dir_port, voter->or_port, voter->contact);
179

180
181
182
183
184
    if (r < 0) {
      log_err(LD_BUG, "Insufficient memory for network status line");
      tor_assert(0);
    }

185
    tor_free(params);
186
    tor_free(flags);
187
    tor_free(methods);
188
189
    outp = status + strlen(status);
    endp = status + len;
190
191
192
193

    if (!tor_digest_is_zero(voter->legacy_id_digest)) {
      char fpbuf[HEX_DIGEST_LEN+1];
      base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
194
195
196
197
198
      r = tor_snprintf(outp, endp-outp, "legacy-dir-key %s\n", fpbuf);
      if (r < 0) {
        log_err(LD_BUG, "Insufficient memory for legacy-dir-key line");
        tor_assert(0);
      }
199
200
201
      outp += strlen(outp);
    }

202
203
204
205
206
    tor_assert(outp + cert->cache_info.signed_descriptor_len < endp);
    memcpy(outp, cert->cache_info.signed_descriptor_body,
           cert->cache_info.signed_descriptor_len);

    outp += cert->cache_info.signed_descriptor_len;
207
  }
208

209
210
211
  SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
                          vrs) {
    vote_microdesc_hash_t *h;
212
    if (routerstatus_format_entry(outp, endp-outp, &vrs->status,
213
                                  vrs->version, NS_V3_VOTE) < 0) {
214
215
216
217
      log_warn(LD_BUG, "Unable to print router status.");
      goto err;
    }
    outp += strlen(outp);
218
219
220
221
222
223
224
225
226
227

    for (h = vrs->microdesc; h; h = h->next) {
      size_t mlen = strlen(h->microdesc_hash_line);
      if (outp+mlen >= endp) {
        log_warn(LD_BUG, "Can't fit microdesc line in vote.");
      }
      memcpy(outp, h->microdesc_hash_line, mlen+1);
      outp += strlen(outp);
    }
  } SMARTLIST_FOREACH_END(vrs);
228

229
230
231
232
233
  r = tor_snprintf(outp, endp-outp, "directory-footer\n");
  if (r < 0) {
    log_err(LD_BUG, "Insufficient memory for directory-footer line");
    tor_assert(0);
  }
234
235
  outp += strlen(outp);

236
237
238
239
240
  {
    char signing_key_fingerprint[FINGERPRINT_LEN+1];
    if (tor_snprintf(outp, endp-outp, "directory-signature ")<0) {
      log_warn(LD_BUG, "Unable to start signature line.");
      goto err;
241
    }
242
    outp += strlen(outp);
243

244
245
246
247
248
249
250
251
252
253
254
    if (crypto_pk_get_fingerprint(private_signing_key,
                                  signing_key_fingerprint, 0)<0) {
      log_warn(LD_BUG, "Unable to get fingerprint for signing key");
      goto err;
    }
    if (tor_snprintf(outp, endp-outp, "%s %s\n", fingerprint,
                     signing_key_fingerprint)<0) {
      log_warn(LD_BUG, "Unable to end signature line.");
      goto err;
    }
    outp += strlen(outp);
255
256
  }

257
  if (router_get_networkstatus_v3_hash(status, digest, DIGEST_SHA1)<0)
258
259
    goto err;
  note_crypto_pk_op(SIGN_DIR);
260
  if (router_append_dirobj_signature(outp,endp-outp,digest, DIGEST_LEN,
261
262
263
264
                                     private_signing_key)<0) {
    log_warn(LD_BUG, "Unable to sign networkstatus vote.");
    goto err;
  }
265

266
  {
267
    networkstatus_t *v;
268
269
270
271
272
    if (!(v = networkstatus_parse_vote_from_string(status, NULL,
                                                   v3_ns->type))) {
      log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
              "<<%s>>",
              v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
273
274
275
276
277
278
279
280
281
282
283
284
      goto err;
    }
    networkstatus_vote_free(v);
  }

  goto done;

 err:
  tor_free(status);
 done:
  tor_free(version_lines);
  return status;
285
286
}

287
288
289
290
/* =====
 * Consensus generation
 * ===== */

291
/** Given a vote <b>vote</b> (not a consensus!), return its associated
292
 * networkstatus_voter_info_t. */
293
static networkstatus_voter_info_t *
294
get_voter(const networkstatus_t *vote)
295
296
{
  tor_assert(vote);
297
  tor_assert(vote->type == NS_TYPE_VOTE);
298
299
300
301
302
  tor_assert(vote->voters);
  tor_assert(smartlist_len(vote->voters) == 1);
  return smartlist_get(vote->voters, 0);
}

303
304
/** Return the signature made by <b>voter</b> using the algorithm
 * <b>alg</b>, or NULL if none is found. */
305
306
307
308
309
310
311
312
313
314
315
316
document_signature_t *
voter_get_sig_by_algorithm(const networkstatus_voter_info_t *voter,
                           digest_algorithm_t alg)
{
  if (!voter->sigs)
    return NULL;
  SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
    if (sig->alg == alg)
      return sig);
  return NULL;
}

317
318
319
/** Temporary structure used in constructing a list of dir-source entries
 * for a consensus.  One of these is generated for every vote, and one more
 * for every legacy key in each vote. */
320
typedef struct dir_src_ent_t {
321
322
323
324
325
  networkstatus_t *v;
  const char *digest;
  int is_legacy;
} dir_src_ent_t;

326
/** Helper for sorting networkstatus_t votes (not consensuses) by the
327
 * hash of their voters' identity digests. */
328
329
330
static int
_compare_votes_by_authority_id(const void **_a, const void **_b)
{
331
  const networkstatus_t *a = *_a, *b = *_b;
332
333
  return memcmp(get_voter(a)->identity_digest,
                get_voter(b)->identity_digest, DIGEST_LEN);
334
335
}

336
337
338
/** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
 * their identity digests, and return -1, 0, or 1 depending on their
 * ordering */
339
340
341
342
343
344
345
346
347
348
349
350
351
static int
_compare_dir_src_ents_by_authority_id(const void **_a, const void **_b)
{
  const dir_src_ent_t *a = *_a, *b = *_b;
  const networkstatus_voter_info_t *a_v = get_voter(a->v),
    *b_v = get_voter(b->v);
  const char *a_id, *b_id;
  a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
  b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;

  return memcmp(a_id, b_id, DIGEST_LEN);
}

352
353
/** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
 * that occurs more than <b>min</b> times. */
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
static void
get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
{
  char *cur = NULL;
  int count = 0;
  SMARTLIST_FOREACH(in, char *, cp,
  {
    if (cur && !strcmp(cp, cur)) {
      ++count;
    } else {
      if (count > min)
        smartlist_add(out, cur);
      cur = cp;
      count = 1;
    }
  });
  if (count > min)
    smartlist_add(out, cur);
}

374
/** Given a sorted list of strings <b>lst</b>, return the member that appears
375
 * most.  Break ties in favor of later-occurring members. */
376
377
#define get_most_frequent_member(lst)           \
  smartlist_get_most_frequent_string(lst)
378

379
380
381
/** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
 * that come from the same routerinfo, with the same derived elements.
 */
382
static int
383
compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
384
385
{
  int r;
386
387
388
  if ((r = memcmp(a->status.identity_digest, b->status.identity_digest,
                  DIGEST_LEN)))
    return r;
389
390
391
  if ((r = memcmp(a->status.descriptor_digest, b->status.descriptor_digest,
                  DIGEST_LEN)))
    return r;
392
  if ((r = (int)(b->status.published_on - a->status.published_on)))
393
    return r;
394
395
  if ((r = strcmp(b->status.nickname, a->status.nickname)))
    return r;
396
397
  if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
    return r;
398
399
400
401
402
403
404
  if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
    return r;
  if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
    return r;
  return 0;
}

405
/** Helper for sorting routerlists based on compare_vote_rs. */
406
static int
407
_compare_vote_rs(const void **_a, const void **_b)
408
409
{
  const vote_routerstatus_t *a = *_a, *b = *_b;
410
  return compare_vote_rs(a,b);
411
412
}

413
414
/** Given a list of vote_routerstatus_t, all for the same router identity,
 * return whichever is most frequent, breaking ties in favor of more
415
 * recently published vote_routerstatus_t and in case of ties there,
Nick Mathewson's avatar
Nick Mathewson committed
416
 * in favor of smaller descriptor digest.
417
 */
418
static vote_routerstatus_t *
419
420
compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
                               char *microdesc_digest256_out)
421
422
423
424
425
{
  vote_routerstatus_t *most = NULL, *cur = NULL;
  int most_n = 0, cur_n = 0;
  time_t most_published = 0;

426
427
428
429
  /* _compare_vote_rs() sorts the items by identity digest (all the same),
   * then by SD digest.  That way, if we have a tie that the published_on
   * date cannot tie, we use the descriptor with the smaller digest.
   */
430
  smartlist_sort(votes, _compare_vote_rs);
431
432
  SMARTLIST_FOREACH(votes, vote_routerstatus_t *, rs,
  {
433
    if (cur && !compare_vote_rs(cur, rs)) {
434
435
436
      ++cur_n;
    } else {
      if (cur_n > most_n ||
437
438
          (cur && cur_n == most_n &&
           cur->status.published_on > most_published)) {
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
        most = cur;
        most_n = cur_n;
        most_published = cur->status.published_on;
      }
      cur_n = 1;
      cur = rs;
    }
  });

  if (cur_n > most_n ||
      (cur && cur_n == most_n && cur->status.published_on > most_published)) {
    most = cur;
    most_n = cur_n;
    most_published = cur->status.published_on;
  }

  tor_assert(most);
456
457
458
459
460

  if (consensus_method >= MIN_METHOD_FOR_MICRODESC &&
      microdesc_digest256_out) {
    smartlist_t *digests = smartlist_create();
    const char *best_microdesc_digest;
461
    SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
462
463
464
        char d[DIGEST256_LEN];
        if (compare_vote_rs(rs, most))
          continue;
465
466
        if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
                                                   DIGEST_SHA256))
467
          smartlist_add(digests, tor_memdup(d, sizeof(d)));
468
    } SMARTLIST_FOREACH_END(rs);
469
470
471
472
473
474
475
476
    smartlist_sort_digests256(digests);
    best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
    if (best_microdesc_digest)
      memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
    SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
    smartlist_free(digests);
  }

477
478
479
  return most;
}

480
481
482
/** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
 * at <b>digest_out</b> to the hash of the concatenation of those strings,
 * computed with the algorithm <b>alg</b>. */
483
static void
484
485
hash_list_members(char *digest_out, size_t len_out,
                  smartlist_t *lst, digest_algorithm_t alg)
486
{
487
488
489
490
491
  crypto_digest_env_t *d;
  if (alg == DIGEST_SHA1)
    d = crypto_new_digest_env();
  else
    d = crypto_new_digest256_env(alg);
492
493
  SMARTLIST_FOREACH(lst, const char *, cp,
                    crypto_digest_add_bytes(d, cp, strlen(cp)));
494
  crypto_digest_get_digest(d, digest_out, len_out);
495
496
  crypto_free_digest_env(d);
}
497

498
499
500
/** Sorting helper: compare two strings based on their values as base-ten
 * positive integers. (Non-integers are treated as prior to all integers, and
 * compared lexically.) */
501
502
503
504
505
506
static int
_cmp_int_strings(const void **_a, const void **_b)
{
  const char *a = *_a, *b = *_b;
  int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
  int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
507
  if (ai<bi) {
508
    return -1;
509
510
511
  } else if (ai==bi) {
    if (ai == 0) /* Parsing failed. */
      return strcmp(a, b);
512
    return 0;
513
  } else {
514
    return 1;
515
  }
516
517
}

518
519
/** Given a list of networkstatus_t votes, determine and return the number of
 * the highest consensus method that is supported by 2/3 of the voters. */
520
521
522
523
524
525
526
527
528
static int
compute_consensus_method(smartlist_t *votes)
{
  smartlist_t *all_methods = smartlist_create();
  smartlist_t *acceptable_methods = smartlist_create();
  smartlist_t *tmp = smartlist_create();
  int min = (smartlist_len(votes) * 2) / 3;
  int n_ok;
  int result;
529
  SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
  {
    tor_assert(vote->supported_methods);
    smartlist_add_all(tmp, vote->supported_methods);
    smartlist_sort(tmp, _cmp_int_strings);
    smartlist_uniq(tmp, _cmp_int_strings, NULL);
    smartlist_add_all(all_methods, tmp);
    smartlist_clear(tmp);
  });

  smartlist_sort(all_methods, _cmp_int_strings);
  get_frequent_members(acceptable_methods, all_methods, min);
  n_ok = smartlist_len(acceptable_methods);
  if (n_ok) {
    const char *best = smartlist_get(acceptable_methods, n_ok-1);
    result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
  } else {
    result = 1;
  }
  smartlist_free(tmp);
  smartlist_free(all_methods);
  smartlist_free(acceptable_methods);
  return result;
}

554
/** Return true iff <b>method</b> is a consensus method that we support. */
555
556
557
static int
consensus_method_is_supported(int method)
{
558
559
560
561
562
563
  return (method >= 1) && (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
}

/** Return a newly allocated string holding the numbers between low and high
 * (inclusive) that are supported consensus methods. */
static char *
564
make_consensus_method_list(int low, int high, const char *separator)
565
566
567
568
569
570
571
572
573
574
575
576
577
{
  char *list;

  char b[32];
  int i;
  smartlist_t *lst;
  lst = smartlist_create();
  for (i = low; i <= high; ++i) {
    if (!consensus_method_is_supported(i))
      continue;
    tor_snprintf(b, sizeof(b), "%d", i);
    smartlist_add(lst, tor_strdup(b));
  }
578
  list = smartlist_join_strings(lst, separator, 0, NULL);
579
580
581
582
  tor_assert(list);
  SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
  smartlist_free(lst);
  return list;
583
584
}

585
/** Helper: given <b>lst</b>, a list of version strings such that every
Nick Mathewson's avatar
Nick Mathewson committed
586
 * version appears once for every versioning voter who recommends it, return a
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
 * newly allocated string holding the resulting client-versions or
 * server-versions list. May change contents of <b>lst</b> */
static char *
compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
{
  int min = n_versioning / 2;
  smartlist_t *good = smartlist_create();
  char *result;
  sort_version_list(lst, 0);
  get_frequent_members(good, lst, min);
  result = smartlist_join_strings(good, ",", 0, NULL);
  smartlist_free(good);
  return result;
}

602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/** Helper: given a list of valid networkstatus_t, return a new string
 * containing the contents of the consensus network parameter set.
 */
/* private */ char *
dirvote_compute_params(smartlist_t *votes)
{
  int i;
  int32_t *vals;

  int cur_param_len;
  const char *cur_param;
  const char *eq;
  char *result;

  const int n_votes = smartlist_len(votes);
  smartlist_t *output;
  smartlist_t *param_list = smartlist_create();

  /* We require that the parameter lists in the votes are well-formed: that
     is, that their keywords are unique and sorted, and that their values are
     between INT32_MIN and INT32_MAX inclusive.  This should be guaranteed by
     the parsing code. */

  vals = tor_malloc(sizeof(int)*n_votes);

  SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
    if (!v->net_params)
      continue;
    smartlist_add_all(param_list, v->net_params);
  } SMARTLIST_FOREACH_END(v);

  if (smartlist_len(param_list) == 0) {
    tor_free(vals);
    smartlist_free(param_list);
    return NULL;
  }

  smartlist_sort_strings(param_list);
  i = 0;
  cur_param = smartlist_get(param_list, 0);
  eq = strchr(cur_param, '=');
  tor_assert(eq);
Sebastian Hahn's avatar
Sebastian Hahn committed
644
  cur_param_len = (int)(eq+1 - cur_param);
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671

  output = smartlist_create();

  SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
    const char *next_param;
    int ok=0;
    eq = strchr(param, '=');
    tor_assert(i<n_votes);
    vals[i++] = (int32_t)
      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
    tor_assert(ok);

    if (param_sl_idx+1 == smartlist_len(param_list))
      next_param = NULL;
    else
      next_param = smartlist_get(param_list, param_sl_idx+1);
    if (!next_param || strncmp(next_param, param, cur_param_len)) {
      /* We've reached the end of a series. */
      int32_t median = median_int32(vals, i);
      char *out_string = tor_malloc(64+cur_param_len);
      memcpy(out_string, param, cur_param_len);
      tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
      smartlist_add(output, out_string);

      i = 0;
      if (next_param) {
        eq = strchr(next_param, '=');
Sebastian Hahn's avatar
Sebastian Hahn committed
672
        cur_param_len = (int)(eq+1 - next_param);
673
674
675
676
677
678
679
680
681
682
683
684
      }
    }
  } SMARTLIST_FOREACH_END(param);

  result = smartlist_join_strings(output, " ", 0, NULL);
  SMARTLIST_FOREACH(output, char *, cp, tor_free(cp));
  smartlist_free(output);
  smartlist_free(param_list);
  tor_free(vals);
  return result;
}

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
       ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
        (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
        (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
        (g) >= 0 && (g) <= (mx))

#define CHECK_EQ(a, b, margin) \
     ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))

typedef enum {
 BW_WEIGHTS_NO_ERROR = 0,
 BW_WEIGHTS_RANGE_ERROR = 1,
 BW_WEIGHTS_SUMG_ERROR = 2,
 BW_WEIGHTS_SUME_ERROR = 3,
 BW_WEIGHTS_SUMD_ERROR = 4,
 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
 BW_WEIGHTS_BALANCE_EG_ERROR = 6
} bw_weights_error_t;

/**
 * Verify that any weightings satisfy the balanced formulas.
 */
static bw_weights_error_t
networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
                            int64_t Wme, int64_t Wmd, int64_t Wee,
                            int64_t Wed, int64_t scale, int64_t G,
                            int64_t M, int64_t E, int64_t D, int64_t T,
                            int64_t margin, int do_balance) {
  bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;

  // Wed + Wmd + Wgd == 1
  if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
    berr = BW_WEIGHTS_SUMD_ERROR;
    goto out;
  }

  // Wmg + Wgg == 1
  if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
    berr = BW_WEIGHTS_SUMG_ERROR;
    goto out;
  }

  // Wme + Wee == 1
  if (!CHECK_EQ(Wme + Wee, scale, margin)) {
    berr = BW_WEIGHTS_SUME_ERROR;
    goto out;
  }

  // Verify weights within range 0->1
  if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
    berr = BW_WEIGHTS_RANGE_ERROR;
    goto out;
  }

  if (do_balance) {
    // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
    if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
      berr = BW_WEIGHTS_BALANCE_EG_ERROR;
      goto out;
    }

    // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
    if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
                (margin*T)/3)) {
      berr = BW_WEIGHTS_BALANCE_MID_ERROR;
      goto out;
    }
  }

out:
  if (berr) {
    log_info(LD_DIR,
             "Bw weight mismatch %d. G="I64_FORMAT" M="I64_FORMAT
             " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
759
760
761
             berr,
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
  }

  return berr;
}

static void
networkstatus_compute_bw_weights_v9(smartlist_t *chunks, int64_t G, int64_t M,
                              int64_t E, int64_t D, int64_t T,
                              int64_t weight_scale)
{
  int64_t Wgg = -1, Wgd = -1;
  int64_t Wmg = -1, Wme = -1, Wmd = -1;
  int64_t Wed = -1, Wee = -1;
  const char *casename;
  char buf[512];
  int r;

Mike Perry's avatar
Mike Perry committed
779
780
781
782
  if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
    log_warn(LD_DIR, "Consensus with empty bandwidth: "
                     "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
                     " D="I64_FORMAT" T="I64_FORMAT,
783
784
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
Mike Perry's avatar
Mike Perry committed
785
786
787
    return;
  }

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
  /*
   * Computed from cases in 3.4.3 of dir-spec.txt
   *
   * 1. Neither are scarce
   * 2. Both Guard and Exit are scarce
   *    a. R+D <= S
   *    b. R+D > S
   * 3. One of Guard or Exit is scarce
   *    a. S+D < T/3
   *    b. S+D >= T/3
   */
  if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
    bw_weights_error_t berr = 0;
    /* Case 1: Neither are scarce.
     *
     * Attempt to ensure that we have a large amount of exit bandwidth
     * in the middle position.
     */
    casename = "Case 1 (Wme*E = Wmd*D)";
    Wgg = (weight_scale*(D+E+G+M))/(3*G);
    if (D==0) Wmd = 0;
    else Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
    Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
    Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
    Wgd = 0;
    Wmg = weight_scale - Wgg;
    Wed = weight_scale - Wmd;

    berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
                                       weight_scale, G, M, E, D, T, 10, 1);

    if (berr) {
      log_warn(LD_DIR, "Bw Weights error %d for case %s. "
                       "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
                       " D="I64_FORMAT" T="I64_FORMAT,
823
824
825
               berr, casename,
               I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
               I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
    }
  } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
    int64_t R = MIN(E, G);
    int64_t S = MAX(E, G);
    /*
     * Case 2: Both Guards and Exits are scarce
     * Balance D between E and G, depending upon
     * D capacity and scarcity.
     */
    if (R+D < S) { // Subcase a
      Wgg = weight_scale;
      Wee = weight_scale;
      Wmg = 0;
      Wme = 0;
      Wmd = 0;
      if (E < G) {
        casename = "Case 2a (E scarce)";
        Wed = weight_scale;
        Wgd = 0;
845
      } else { /* E >= G */
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
        casename = "Case 2a (G scarce)";
        Wed = 0;
        Wgd = weight_scale;
      }
    } else { // Subcase b: R+D > S
      bw_weights_error_t berr = 0;
      casename = "Case 2b (Wme*E == Wmd*D)";
      if (D != 0) {
        Wgg = weight_scale;
        Wgd = (weight_scale*(D + E - 2*G + M))/(3*D); // T/3 >= G (Ok)
        Wmd = (weight_scale*(D + E + G - 2*M))/(6*D); // T/3 >= M
        Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
        Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E); // 2E+M >= T/3
        Wmg = 0;
        Wed = weight_scale - Wgd - Wmd;

        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
                                       weight_scale, G, M, E, D, T, 10, 1);
      }

      if (D == 0 || berr) { // Can happen if M > T/3
        casename = "Case 2b (E=G)";
        Wgg = weight_scale;
        Wee = weight_scale;
        Wmg = 0;
        Wme = 0;
        Wmd = 0;
        if (D == 0) Wgd = 0;
        else Wgd = (weight_scale*(D+E-G))/(2*D);
        Wed = weight_scale - Wgd;
        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
                Wed, weight_scale, G, M, E, D, T, 10, 1);
      }
      if (berr != BW_WEIGHTS_NO_ERROR &&
              berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
        log_warn(LD_DIR, "Bw Weights error %d for case %s. "
                         "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
                         " D="I64_FORMAT" T="I64_FORMAT,
884
885
886
                 berr, casename,
                 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
                 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
887
888
889
890
891
892
893
894
895
      }
    }
  } else { // if (E < T/3 || G < T/3) {
    int64_t S = MIN(E, G);
    // Case 3: Exactly one of Guard or Exit is scarce
    if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
      log_warn(LD_BUG,
           "Bw-Weights Case 3 but with G="I64_FORMAT" M="
           I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
896
897
               I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
               I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
    }

    if (3*(S+D) < T) { // Subcase a: S+D < T/3
      if (G < E) {
        casename = "Case 3a (G scarce)";
        Wgg = Wgd = weight_scale;
        Wmd = Wed = Wmg = 0;
        // Minor subcase, if E is more scarce than M,
        // keep its bandwidth in place.
        if (E < M) Wme = 0;
        else Wme = (weight_scale*(E-M))/(2*E);
        Wee = weight_scale-Wme;
      } else { // G >= E
        casename = "Case 3a (E scarce)";
        Wee = Wed = weight_scale;
        Wmd = Wgd = Wme = 0;
        // Minor subcase, if G is more scarce than M,
        // keep its bandwidth in place.
        if (G < M) Wmg = 0;
        else Wmg = (weight_scale*(G-M))/(2*G);
        Wgg = weight_scale-Wmg;
      }
    } else { // Subcase b: S+D >= T/3
      bw_weights_error_t berr = 0;
      // D != 0 because S+D >= T/3
      if (G < E) {
        casename = "Case 3b (G scarce, Wme*E == Wmd*D)";
        Wgd = (weight_scale*(D + E - 2*G + M))/(3*D);
        Wmd = (weight_scale*(D + E + G - 2*M))/(6*D);
        Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
        Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E);
        Wgg = weight_scale;
        Wmg = 0;
        Wed = weight_scale - Wgd - Wmd;

        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
                    Wed, weight_scale, G, M, E, D, T, 10, 1);
      } else { // G >= E
        casename = "Case 3b (E scarce, Wme*E == Wmd*D)";
        Wgg = (weight_scale*(D + E + G + M))/(3*G);
        Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
        Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
        Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
        Wgd = 0;
        Wmg = weight_scale - Wgg;
        Wed = weight_scale - Wmd;

        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
                      Wed, weight_scale, G, M, E, D, T, 10, 1);
      }
      if (berr) {
        log_warn(LD_DIR, "Bw Weights error %d for case %s. "
                         "G="I64_FORMAT" M="I64_FORMAT
                         " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
952
953
954
                 berr, casename,
               I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
               I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
955
956
957
958
      }
    }
  }

959
960
961
962
963
  /* We cast down the weights to 32 bit ints on the assumption that
   * weight_scale is ~= 10000. We need to ensure a rogue authority
   * doesn't break this assumption to rig our weights */
  tor_assert(0 < weight_scale && weight_scale < INT32_MAX);

964
965
966
967
  if (Wgg < 0 || Wgg > weight_scale) {
    log_warn(LD_DIR, "Bw %s: Wgg="I64_FORMAT"! G="I64_FORMAT
            " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
            " T="I64_FORMAT,
968
969
970
971
             casename, I64_PRINTF_ARG(Wgg),
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));

972
973
974
975
976
977
    Wgg = MAX(MIN(Wgg, weight_scale), 0);
  }
  if (Wgd < 0 || Wgd > weight_scale) {
    log_warn(LD_DIR, "Bw %s: Wgd="I64_FORMAT"! G="I64_FORMAT
            " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
            " T="I64_FORMAT,
978
979
980
             casename, I64_PRINTF_ARG(Wgd),
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
981
982
983
984
985
986
    Wgd = MAX(MIN(Wgd, weight_scale), 0);
  }
  if (Wmg < 0 || Wmg > weight_scale) {
    log_warn(LD_DIR, "Bw %s: Wmg="I64_FORMAT"! G="I64_FORMAT
            " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
            " T="I64_FORMAT,
987
988
989
             casename, I64_PRINTF_ARG(Wmg),
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
990
991
992
993
994
995
    Wmg = MAX(MIN(Wmg, weight_scale), 0);
  }
  if (Wme < 0 || Wme > weight_scale) {
    log_warn(LD_DIR, "Bw %s: Wme="I64_FORMAT"! G="I64_FORMAT
            " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
            " T="I64_FORMAT,
996
997
998
             casename, I64_PRINTF_ARG(Wme),
             I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
             I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
999
1000
    Wme = MAX(MIN(Wme, weight_scale), 0);
  }
For faster browsing, not all history is shown. View entire blame