dirvote.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char dirvote_c_id[] =
  7. "$Id$";
  8. #define DIRVOTE_PRIVATE
  9. #include "or.h"
  10. /**
  11. * \file dirvote.c
  12. * \brief Functions to compute directory consensus, and schedule voting.
  13. **/
  14. static int dirvote_add_signatures_to_pending_consensus(
  15. const char *detached_signatures_body,
  16. const char **msg_out);
  17. static char *list_v3_auth_ids(void);
  18. static void dirvote_fetch_missing_votes(void);
  19. static void dirvote_fetch_missing_signatures(void);
  20. static int dirvote_perform_vote(void);
  21. static void dirvote_clear_votes(int all_votes);
  22. static int dirvote_compute_consensus(void);
  23. static int dirvote_publish_consensus(void);
  24. /* =====
  25. * Voting
  26. * =====*/
  27. /** Return a new string containing the string representation of the vote in
  28. * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
  29. * For v3 authorities. */
  30. char *
  31. format_networkstatus_vote(crypto_pk_env_t *private_signing_key,
  32. networkstatus_t *v3_ns)
  33. {
  34. /** Amount of space to allocate for each entry: r, s, and v lines. */
  35. #define RS_ENTRY_LEN \
  36. ( /* first line */ \
  37. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  38. 5*2 /* ports */ + 10 /* punctuation */ + \
  39. /* second line */ \
  40. MAX_FLAG_LINE_LEN + \
  41. /* v line. */ \
  42. MAX_V_LINE_LEN \
  43. )
  44. size_t len;
  45. char *status = NULL;
  46. const char *client_versions = NULL, *server_versions = NULL;
  47. char *outp, *endp;
  48. char fingerprint[FINGERPRINT_LEN+1];
  49. char ipaddr[INET_NTOA_BUF_LEN];
  50. char digest[DIGEST_LEN];
  51. struct in_addr in;
  52. uint32_t addr;
  53. routerlist_t *rl = router_get_routerlist();
  54. char *version_lines = NULL;
  55. networkstatus_voter_info_t *voter;
  56. tor_assert(private_signing_key);
  57. voter = smartlist_get(v3_ns->voters, 0);
  58. addr = voter->addr;
  59. in.s_addr = htonl(addr);
  60. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  61. base16_encode(fingerprint, sizeof(fingerprint),
  62. v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
  63. client_versions = v3_ns->client_versions;
  64. server_versions = v3_ns->server_versions;
  65. if (client_versions || server_versions) {
  66. size_t v_len = 64;
  67. char *cp;
  68. if (client_versions)
  69. v_len += strlen(client_versions);
  70. if (server_versions)
  71. v_len += strlen(server_versions);
  72. version_lines = tor_malloc(v_len);
  73. cp = version_lines;
  74. if (client_versions) {
  75. tor_snprintf(cp, v_len-(cp-version_lines),
  76. "client-versions %s\n", client_versions);
  77. cp += strlen(cp);
  78. }
  79. if (server_versions)
  80. tor_snprintf(cp, v_len-(cp-version_lines),
  81. "server-versions %s\n", server_versions);
  82. } else {
  83. version_lines = tor_strdup("");
  84. }
  85. len = 8192;
  86. len += strlen(version_lines);
  87. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  88. len += v3_ns->cert->cache_info.signed_descriptor_len;
  89. status = tor_malloc(len);
  90. {
  91. char published[ISO_TIME_LEN+1];
  92. char va[ISO_TIME_LEN+1];
  93. char fu[ISO_TIME_LEN+1];
  94. char vu[ISO_TIME_LEN+1];
  95. char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
  96. authority_cert_t *cert = v3_ns->cert;
  97. format_iso_time(published, v3_ns->published);
  98. format_iso_time(va, v3_ns->valid_after);
  99. format_iso_time(fu, v3_ns->fresh_until);
  100. format_iso_time(vu, v3_ns->valid_until);
  101. tor_assert(cert);
  102. tor_snprintf(status, len,
  103. "network-status-version 3\n"
  104. "vote-status vote\n"
  105. "consensus-methods 1 2\n"
  106. "published %s\n"
  107. "valid-after %s\n"
  108. "fresh-until %s\n"
  109. "valid-until %s\n"
  110. "voting-delay %d %d\n"
  111. "%s" /* versions */
  112. "known-flags %s\n"
  113. "dir-source %s %s %s %s %d %d\n"
  114. "contact %s\n",
  115. published, va, fu, vu,
  116. v3_ns->vote_seconds, v3_ns->dist_seconds,
  117. version_lines,
  118. flags,
  119. voter->nickname, fingerprint, voter->address,
  120. ipaddr, voter->dir_port, voter->or_port, voter->contact);
  121. tor_free(flags);
  122. outp = status + strlen(status);
  123. endp = status + len;
  124. tor_assert(outp + cert->cache_info.signed_descriptor_len < endp);
  125. memcpy(outp, cert->cache_info.signed_descriptor_body,
  126. cert->cache_info.signed_descriptor_len);
  127. outp += cert->cache_info.signed_descriptor_len;
  128. }
  129. SMARTLIST_FOREACH(v3_ns->routerstatus_list, vote_routerstatus_t *, vrs,
  130. {
  131. if (routerstatus_format_entry(outp, endp-outp, &vrs->status,
  132. vrs->version, 0) < 0) {
  133. log_warn(LD_BUG, "Unable to print router status.");
  134. goto err;
  135. }
  136. outp += strlen(outp);
  137. });
  138. {
  139. char signing_key_fingerprint[FINGERPRINT_LEN+1];
  140. if (tor_snprintf(outp, endp-outp, "directory-signature ")<0) {
  141. log_warn(LD_BUG, "Unable to start signature line.");
  142. goto err;
  143. }
  144. outp += strlen(outp);
  145. if (crypto_pk_get_fingerprint(private_signing_key,
  146. signing_key_fingerprint, 0)<0) {
  147. log_warn(LD_BUG, "Unable to get fingerprint for signing key");
  148. goto err;
  149. }
  150. if (tor_snprintf(outp, endp-outp, "%s %s\n", fingerprint,
  151. signing_key_fingerprint)<0) {
  152. log_warn(LD_BUG, "Unable to end signature line.");
  153. goto err;
  154. }
  155. outp += strlen(outp);
  156. }
  157. if (router_get_networkstatus_v3_hash(status, digest)<0)
  158. goto err;
  159. note_crypto_pk_op(SIGN_DIR);
  160. if (router_append_dirobj_signature(outp,endp-outp,digest,
  161. private_signing_key)<0) {
  162. log_warn(LD_BUG, "Unable to sign networkstatus vote.");
  163. goto err;
  164. }
  165. {
  166. networkstatus_t *v;
  167. if (!(v = networkstatus_parse_vote_from_string(status, NULL, 1))) {
  168. log_err(LD_BUG,"Generated a networkstatus vote we couldn't parse: "
  169. "<<%s>>", status);
  170. goto err;
  171. }
  172. networkstatus_vote_free(v);
  173. }
  174. goto done;
  175. err:
  176. tor_free(status);
  177. done:
  178. tor_free(version_lines);
  179. return status;
  180. }
  181. /* =====
  182. * Consensus generation
  183. * ===== */
  184. /** Given a vote <b>vote</b> (not a consensus!), return its associated
  185. * networkstatus_voter_info_t. */
  186. static networkstatus_voter_info_t *
  187. get_voter(const networkstatus_t *vote)
  188. {
  189. tor_assert(vote);
  190. tor_assert(vote->is_vote);
  191. tor_assert(vote->voters);
  192. tor_assert(smartlist_len(vote->voters) == 1);
  193. return smartlist_get(vote->voters, 0);
  194. }
  195. /** Helper for sorting networkstatus_t votes (not consensuses) by the
  196. * hash of their voters' identity digests. */
  197. static int
  198. _compare_votes_by_authority_id(const void **_a, const void **_b)
  199. {
  200. const networkstatus_t *a = *_a, *b = *_b;
  201. return memcmp(get_voter(a)->identity_digest,
  202. get_voter(b)->identity_digest, DIGEST_LEN);
  203. }
  204. /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
  205. * that occurs more than <b>min</b> times. */
  206. static void
  207. get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
  208. {
  209. char *cur = NULL;
  210. int count = 0;
  211. SMARTLIST_FOREACH(in, char *, cp,
  212. {
  213. if (cur && !strcmp(cp, cur)) {
  214. ++count;
  215. } else {
  216. if (count > min)
  217. smartlist_add(out, cur);
  218. cur = cp;
  219. count = 1;
  220. }
  221. });
  222. if (count > min)
  223. smartlist_add(out, cur);
  224. }
  225. /** Given a sorted list of strings <b>lst</b>, return the member that appears
  226. * most. Break ties in favor of later-occurring members. */
  227. static const char *
  228. get_most_frequent_member(smartlist_t *lst)
  229. {
  230. const char *most_frequent = NULL;
  231. int most_frequent_count = 0;
  232. const char *cur = NULL;
  233. int count = 0;
  234. SMARTLIST_FOREACH(lst, const char *, s,
  235. {
  236. if (cur && !strcmp(s, cur)) {
  237. ++count;
  238. } else {
  239. if (count >= most_frequent_count) {
  240. most_frequent = cur;
  241. most_frequent_count = count;
  242. }
  243. cur = s;
  244. count = 1;
  245. }
  246. });
  247. if (count >= most_frequent_count) {
  248. most_frequent = cur;
  249. most_frequent_count = count;
  250. }
  251. return most_frequent;
  252. }
  253. /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
  254. * that come from the same routerinfo, with the same derived elements.
  255. */
  256. static int
  257. compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
  258. {
  259. int r;
  260. if ((r = memcmp(a->status.identity_digest, b->status.identity_digest,
  261. DIGEST_LEN)))
  262. return r;
  263. if ((r = memcmp(a->status.descriptor_digest, b->status.descriptor_digest,
  264. DIGEST_LEN)))
  265. return r;
  266. if ((r = (b->status.published_on - a->status.published_on)))
  267. return r;
  268. if ((r = strcmp(b->status.nickname, a->status.nickname)))
  269. return r;
  270. if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
  271. return r;
  272. if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
  273. return r;
  274. if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
  275. return r;
  276. return 0;
  277. }
  278. /** Helper for sorting routerlists based on compare_vote_rs. */
  279. static int
  280. _compare_vote_rs(const void **_a, const void **_b)
  281. {
  282. const vote_routerstatus_t *a = *_a, *b = *_b;
  283. return compare_vote_rs(a,b);
  284. }
  285. /** Given a list of vote_routerstatus_t, all for the same router identity,
  286. * return whichever is most frequent, breaking ties in favor of more
  287. * recently published vote_routerstatus_t.
  288. */
  289. static vote_routerstatus_t *
  290. compute_routerstatus_consensus(smartlist_t *votes)
  291. {
  292. vote_routerstatus_t *most = NULL, *cur = NULL;
  293. int most_n = 0, cur_n = 0;
  294. time_t most_published = 0;
  295. smartlist_sort(votes, _compare_vote_rs);
  296. SMARTLIST_FOREACH(votes, vote_routerstatus_t *, rs,
  297. {
  298. if (cur && !compare_vote_rs(cur, rs)) {
  299. ++cur_n;
  300. } else {
  301. if (cur_n > most_n ||
  302. (cur && cur_n == most_n &&
  303. cur->status.published_on > most_published)) {
  304. most = cur;
  305. most_n = cur_n;
  306. most_published = cur->status.published_on;
  307. }
  308. cur_n = 1;
  309. cur = rs;
  310. }
  311. });
  312. if (cur_n > most_n ||
  313. (cur && cur_n == most_n && cur->status.published_on > most_published)) {
  314. most = cur;
  315. most_n = cur_n;
  316. most_published = cur->status.published_on;
  317. }
  318. tor_assert(most);
  319. return most;
  320. }
  321. /** Given a list of strings in <b>lst</b>, set the DIGEST_LEN-byte digest at
  322. * <b>digest_out</b> to the hash of the concatenation of those strings. */
  323. static void
  324. hash_list_members(char *digest_out, smartlist_t *lst)
  325. {
  326. crypto_digest_env_t *d = crypto_new_digest_env();
  327. SMARTLIST_FOREACH(lst, const char *, cp,
  328. crypto_digest_add_bytes(d, cp, strlen(cp)));
  329. crypto_digest_get_digest(d, digest_out, DIGEST_LEN);
  330. crypto_free_digest_env(d);
  331. }
  332. /**DOCDOC*/
  333. static int
  334. _cmp_int_strings(const void **_a, const void **_b)
  335. {
  336. const char *a = *_a, *b = *_b;
  337. int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
  338. int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
  339. if (ai<bi)
  340. return -1;
  341. else if (ai==bi)
  342. return 0;
  343. else
  344. return 1;
  345. }
  346. /**DOCDOC*/
  347. static int
  348. compute_consensus_method(smartlist_t *votes)
  349. {
  350. smartlist_t *all_methods = smartlist_create();
  351. smartlist_t *acceptable_methods = smartlist_create();
  352. smartlist_t *tmp = smartlist_create();
  353. int min = (smartlist_len(votes) * 2) / 3;
  354. int n_ok;
  355. int result;
  356. SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
  357. {
  358. tor_assert(vote->supported_methods);
  359. smartlist_add_all(tmp, vote->supported_methods);
  360. smartlist_sort(tmp, _cmp_int_strings);
  361. smartlist_uniq(tmp, _cmp_int_strings, NULL);
  362. smartlist_add_all(all_methods, tmp);
  363. smartlist_clear(tmp);
  364. });
  365. smartlist_sort(all_methods, _cmp_int_strings);
  366. get_frequent_members(acceptable_methods, all_methods, min);
  367. n_ok = smartlist_len(acceptable_methods);
  368. if (n_ok) {
  369. const char *best = smartlist_get(acceptable_methods, n_ok-1);
  370. result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
  371. } else {
  372. result = 1;
  373. }
  374. smartlist_free(tmp);
  375. smartlist_free(all_methods);
  376. smartlist_free(acceptable_methods);
  377. return result;
  378. }
  379. /**DOCDOC*/
  380. static int
  381. consensus_method_is_supported(int method)
  382. {
  383. return (method >= 1) && (method <= 2);
  384. }
  385. /** Given a list of vote networkstatus_t in <b>votes</b>, our public
  386. * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
  387. * and the number of <b>total_authorities</b> that we believe exist in our
  388. * voting quorum, generate the text of a new v3 consensus vote, and return the
  389. * value in a newly allocated string.
  390. *
  391. * Note: this function DOES NOT check whether the votes are from
  392. * recognized authorities. (dirvote_add_vote does that.) */
  393. char *
  394. networkstatus_compute_consensus(smartlist_t *votes,
  395. int total_authorities,
  396. crypto_pk_env_t *identity_key,
  397. crypto_pk_env_t *signing_key)
  398. {
  399. smartlist_t *chunks;
  400. char *result = NULL;
  401. int consensus_method;
  402. time_t valid_after, fresh_until, valid_until;
  403. int vote_seconds, dist_seconds;
  404. char *client_versions = NULL, *server_versions = NULL;
  405. smartlist_t *flags;
  406. tor_assert(total_authorities >= smartlist_len(votes));
  407. if (!smartlist_len(votes)) {
  408. log_warn(LD_DIR, "Can't compute a consensus from no votes.");
  409. return NULL;
  410. }
  411. flags = smartlist_create();
  412. consensus_method = compute_consensus_method(votes);
  413. if (consensus_method_is_supported(consensus_method)) {
  414. log_info(LD_DIR, "Generating consensus using method %d.",
  415. consensus_method);
  416. } else {
  417. log_warn(LD_DIR, "The other authorities will use consensus method %d, "
  418. "which I don't support. Maybe I should upgrade!",
  419. consensus_method);
  420. consensus_method = 1;
  421. }
  422. /* Compute medians of time-related things, and figure out how many
  423. * routers we might need to talk about. */
  424. {
  425. int n_votes = smartlist_len(votes);
  426. time_t *va_times = tor_malloc(n_votes * sizeof(time_t));
  427. time_t *fu_times = tor_malloc(n_votes * sizeof(time_t));
  428. time_t *vu_times = tor_malloc(n_votes * sizeof(time_t));
  429. int *votesec_list = tor_malloc(n_votes * sizeof(int));
  430. int *distsec_list = tor_malloc(n_votes * sizeof(int));
  431. int n_versioning_clients = 0, n_versioning_servers = 0;
  432. smartlist_t *combined_client_versions = smartlist_create();
  433. smartlist_t *combined_server_versions = smartlist_create();
  434. int j;
  435. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  436. {
  437. tor_assert(v->is_vote);
  438. va_times[v_sl_idx] = v->valid_after;
  439. fu_times[v_sl_idx] = v->fresh_until;
  440. vu_times[v_sl_idx] = v->valid_until;
  441. votesec_list[v_sl_idx] = v->vote_seconds;
  442. distsec_list[v_sl_idx] = v->dist_seconds;
  443. if (v->client_versions) {
  444. smartlist_t *cv = smartlist_create();
  445. ++n_versioning_clients;
  446. smartlist_split_string(cv, v->client_versions, ",",
  447. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  448. sort_version_list(cv, 1);
  449. smartlist_add_all(combined_client_versions, cv);
  450. smartlist_free(cv); /* elements get freed later. */
  451. }
  452. if (v->server_versions) {
  453. smartlist_t *sv = smartlist_create();
  454. ++n_versioning_servers;
  455. smartlist_split_string(sv, v->server_versions, ",",
  456. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  457. sort_version_list(sv, 1);
  458. smartlist_add_all(combined_server_versions, sv);
  459. smartlist_free(sv); /* elements get freed later. */
  460. }
  461. SMARTLIST_FOREACH(v->known_flags, const char *, cp,
  462. smartlist_add(flags, tor_strdup(cp)));
  463. });
  464. valid_after = median_time(va_times, n_votes);
  465. fresh_until = median_time(fu_times, n_votes);
  466. valid_until = median_time(vu_times, n_votes);
  467. vote_seconds = median_int(votesec_list, n_votes);
  468. dist_seconds = median_int(distsec_list, n_votes);
  469. tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
  470. tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
  471. tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
  472. tor_assert(dist_seconds >= MIN_DIST_SECONDS);
  473. for (j = 0; j < 2; ++j) {
  474. smartlist_t *lst =
  475. j ? combined_server_versions : combined_client_versions;
  476. int min = (j ? n_versioning_servers : n_versioning_clients) / 2;
  477. smartlist_t *good = smartlist_create();
  478. char *res;
  479. sort_version_list(lst, 0);
  480. get_frequent_members(good, lst, min);
  481. res = smartlist_join_strings(good, ",", 0, NULL);
  482. if (j)
  483. server_versions = res;
  484. else
  485. client_versions = res;
  486. SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
  487. smartlist_free(good);
  488. smartlist_free(lst);
  489. }
  490. smartlist_sort_strings(flags);
  491. smartlist_uniq_strings(flags);
  492. tor_free(va_times);
  493. tor_free(fu_times);
  494. tor_free(vu_times);
  495. tor_free(votesec_list);
  496. tor_free(distsec_list);
  497. }
  498. chunks = smartlist_create();
  499. {
  500. char buf[1024];
  501. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  502. vu_buf[ISO_TIME_LEN+1];
  503. char *flaglist;
  504. format_iso_time(va_buf, valid_after);
  505. format_iso_time(fu_buf, fresh_until);
  506. format_iso_time(vu_buf, valid_until);
  507. flaglist = smartlist_join_strings(flags, " ", 0, NULL);
  508. smartlist_add(chunks, tor_strdup("network-status-version 3\n"
  509. "vote-status consensus\n"));
  510. if (consensus_method >= 2) {
  511. tor_snprintf(buf, sizeof(buf), "consensus-method %d\n",
  512. consensus_method);
  513. smartlist_add(chunks, tor_strdup(buf));
  514. }
  515. tor_snprintf(buf, sizeof(buf),
  516. "valid-after %s\n"
  517. "fresh-until %s\n"
  518. "valid-until %s\n"
  519. "voting-delay %d %d\n"
  520. "client-versions %s\n"
  521. "server-versions %s\n"
  522. "known-flags %s\n",
  523. va_buf, fu_buf, vu_buf,
  524. vote_seconds, dist_seconds,
  525. client_versions, server_versions, flaglist);
  526. smartlist_add(chunks, tor_strdup(buf));
  527. tor_free(flaglist);
  528. }
  529. /* Sort the votes. */
  530. smartlist_sort(votes, _compare_votes_by_authority_id);
  531. /* Add the authority sections. */
  532. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  533. {
  534. char buf[1024];
  535. struct in_addr in;
  536. char ip[INET_NTOA_BUF_LEN];
  537. char fingerprint[HEX_DIGEST_LEN+1];
  538. char votedigest[HEX_DIGEST_LEN+1];
  539. networkstatus_voter_info_t *voter = get_voter(v);
  540. in.s_addr = htonl(voter->addr);
  541. tor_inet_ntoa(&in, ip, sizeof(ip));
  542. base16_encode(fingerprint, sizeof(fingerprint), voter->identity_digest,
  543. DIGEST_LEN);
  544. base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
  545. DIGEST_LEN);
  546. tor_snprintf(buf, sizeof(buf),
  547. "dir-source %s %s %s %s %d %d\n"
  548. "contact %s\n"
  549. "vote-digest %s\n",
  550. voter->nickname, fingerprint, voter->address, ip,
  551. voter->dir_port,
  552. voter->or_port,
  553. voter->contact,
  554. votedigest);
  555. smartlist_add(chunks, tor_strdup(buf));
  556. });
  557. /* Add the actual router entries. */
  558. {
  559. int *index; /* index[j] is the current index into votes[j]. */
  560. int *size; /* size[j] is the number of routerstatuses in votes[j]. */
  561. int *flag_counts; /* The number of voters that list flag[j] for the
  562. * currently considered router. */
  563. int i;
  564. smartlist_t *matching_descs = smartlist_create();
  565. smartlist_t *chosen_flags = smartlist_create();
  566. smartlist_t *versions = smartlist_create();
  567. int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
  568. * votes[j] knows about. */
  569. int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
  570. * about flags[f]. */
  571. int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
  572. * is the same flag as votes[j]->known_flags[b]. */
  573. int *named_flag; /* Index of the flag "Named" for votes[j] */
  574. int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
  575. int chosen_named_idx, chosen_unnamed_idx;
  576. strmap_t *name_to_id_map = strmap_new();
  577. char conflict[DIGEST_LEN];
  578. char unknown[DIGEST_LEN];
  579. memset(conflict, 0, sizeof(conflict));
  580. memset(unknown, 0xff, sizeof(conflict));
  581. index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  582. size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  583. n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  584. n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
  585. flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  586. named_flag = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  587. unnamed_flag = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  588. for (i = 0; i < smartlist_len(votes); ++i)
  589. unnamed_flag[i] = named_flag[i] = -1;
  590. chosen_named_idx = smartlist_string_pos(flags, "Named");
  591. chosen_unnamed_idx = smartlist_string_pos(flags, "Unnamed");
  592. /* Build the flag index. */
  593. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  594. {
  595. flag_map[v_sl_idx] = tor_malloc_zero(
  596. sizeof(int)*smartlist_len(v->known_flags));
  597. SMARTLIST_FOREACH(v->known_flags, const char *, fl,
  598. {
  599. int p = smartlist_string_pos(flags, fl);
  600. tor_assert(p >= 0);
  601. flag_map[v_sl_idx][fl_sl_idx] = p;
  602. ++n_flag_voters[p];
  603. if (!strcmp(fl, "Named"))
  604. named_flag[v_sl_idx] = fl_sl_idx;
  605. if (!strcmp(fl, "Unnamed"))
  606. unnamed_flag[v_sl_idx] = fl_sl_idx;
  607. });
  608. n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
  609. size[v_sl_idx] = smartlist_len(v->routerstatus_list);
  610. });
  611. /* Named and Unnamed get treated specially */
  612. if (consensus_method >= 2) {
  613. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  614. {
  615. uint64_t nf;
  616. if (named_flag[v_sl_idx]<0)
  617. continue;
  618. nf = U64_LITERAL(1) << named_flag[v_sl_idx];
  619. SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
  620. {
  621. if ((rs->flags & nf) != 0) {
  622. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  623. if (!d) {
  624. /* We have no name officially mapped to this digest. */
  625. strmap_set_lc(name_to_id_map, rs->status.nickname,
  626. rs->status.identity_digest);
  627. } else if (d != conflict &&
  628. memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  629. /* Authorities disagree about this nickname. */
  630. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  631. } else {
  632. /* It's already a conflict, or it's already this ID. */
  633. }
  634. }
  635. });
  636. });
  637. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  638. {
  639. uint64_t uf;
  640. if (unnamed_flag[v_sl_idx]<0)
  641. continue;
  642. uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
  643. SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
  644. {
  645. if ((rs->flags & uf) != 0) {
  646. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  647. if (d == conflict || d == unknown) {
  648. /* Leave it alone; we know what it is. */
  649. } else if (!d) {
  650. /* We have no name officially mapped to this digest. */
  651. strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
  652. } else if (!memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  653. /* Authorities disagree about this nickname. */
  654. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  655. } else {
  656. /* It's mapped to a different name. */
  657. }
  658. }
  659. });
  660. });
  661. }
  662. /* Now go through all the votes */
  663. flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
  664. while (1) {
  665. vote_routerstatus_t *rs;
  666. routerstatus_t rs_out;
  667. const char *lowest_id = NULL;
  668. const char *chosen_version;
  669. const char *chosen_name = NULL;
  670. int is_named = 0, is_unnamed = 0;
  671. int naming_conflict = 0;
  672. int n_listing = 0;
  673. int i;
  674. char buf[256];
  675. /* Of the next-to-be-considered digest in each voter, which is first? */
  676. SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
  677. if (index[v_sl_idx] < size[v_sl_idx]) {
  678. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  679. if (!lowest_id ||
  680. memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN) < 0)
  681. lowest_id = rs->status.identity_digest;
  682. }
  683. });
  684. if (!lowest_id) /* we're out of routers. */
  685. break;
  686. memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
  687. smartlist_clear(matching_descs);
  688. smartlist_clear(chosen_flags);
  689. smartlist_clear(versions);
  690. /* Okay, go through all the entries for this digest. */
  691. SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
  692. if (index[v_sl_idx] >= size[v_sl_idx])
  693. continue; /* out of entries. */
  694. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  695. if (memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
  696. continue; /* doesn't include this router. */
  697. /* At this point, we know that we're looking at a routersatus with
  698. * identity "lowest".
  699. */
  700. ++index[v_sl_idx];
  701. ++n_listing;
  702. smartlist_add(matching_descs, rs);
  703. if (rs->version && rs->version[0])
  704. smartlist_add(versions, rs->version);
  705. /* Tally up all the flags. */
  706. for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
  707. if (rs->flags & (U64_LITERAL(1) << i))
  708. ++flag_counts[flag_map[v_sl_idx][i]];
  709. }
  710. if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
  711. if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
  712. log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
  713. chosen_name, rs->status.nickname);
  714. naming_conflict = 1;
  715. }
  716. chosen_name = rs->status.nickname;
  717. }
  718. });
  719. /* We don't include this router at all unless more than half of
  720. * the authorities we believe in list it. */
  721. if (n_listing <= total_authorities/2)
  722. continue;
  723. /* Figure out the most popular opinion of what the most recent
  724. * routerinfo and its contents are. */
  725. rs = compute_routerstatus_consensus(matching_descs);
  726. /* Copy bits of that into rs_out. */
  727. tor_assert(!memcmp(lowest_id, rs->status.identity_digest, DIGEST_LEN));
  728. memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
  729. memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
  730. DIGEST_LEN);
  731. rs_out.addr = rs->status.addr;
  732. rs_out.published_on = rs->status.published_on;
  733. rs_out.dir_port = rs->status.dir_port;
  734. rs_out.or_port = rs->status.or_port;
  735. if (chosen_name && !naming_conflict) {
  736. strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
  737. } else {
  738. strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
  739. }
  740. if (consensus_method == 1) {
  741. is_named = chosen_named_idx >= 0 &&
  742. (!naming_conflict && flag_counts[chosen_named_idx]);
  743. } else {
  744. const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
  745. if (!d) {
  746. is_named = is_unnamed = 0;
  747. } else if (!memcmp(d, lowest_id, DIGEST_LEN)) {
  748. is_named = 1; is_unnamed = 0;
  749. } else {
  750. is_named = 0; is_unnamed = 1;
  751. }
  752. }
  753. /* Set the flags. */
  754. smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
  755. SMARTLIST_FOREACH(flags, const char *, fl,
  756. {
  757. if (!strcmp(fl, "Named")) {
  758. if (is_named)
  759. smartlist_add(chosen_flags, (char*)fl);
  760. } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
  761. if (is_unnamed)
  762. smartlist_add(chosen_flags, (char*)fl);
  763. } else {
  764. if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2)
  765. smartlist_add(chosen_flags, (char*)fl);
  766. }
  767. });
  768. /* Pick the version. */
  769. if (smartlist_len(versions)) {
  770. sort_version_list(versions, 0);
  771. chosen_version = get_most_frequent_member(versions);
  772. } else {
  773. chosen_version = NULL;
  774. }
  775. /* Okay!! Now we can write the descriptor... */
  776. /* First line goes into "buf". */
  777. routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL, 1);
  778. smartlist_add(chunks, tor_strdup(buf));
  779. /* Second line is all flags. The "\n" is missing. */
  780. smartlist_add(chunks,
  781. smartlist_join_strings(chosen_flags, " ", 0, NULL));
  782. /* Now the version line. */
  783. if (chosen_version) {
  784. smartlist_add(chunks, tor_strdup("\nv "));
  785. smartlist_add(chunks, tor_strdup(chosen_version));
  786. }
  787. smartlist_add(chunks, tor_strdup("\n"));
  788. /* And the loop is over and we move on to the next router */
  789. }
  790. tor_free(index);
  791. tor_free(size);
  792. tor_free(n_voter_flags);
  793. tor_free(n_flag_voters);
  794. for (i = 0; i < smartlist_len(votes); ++i)
  795. tor_free(flag_map[i]);
  796. tor_free(flag_map);
  797. tor_free(flag_counts);
  798. tor_free(named_flag);
  799. tor_free(unnamed_flag);
  800. strmap_free(name_to_id_map, NULL);
  801. smartlist_free(matching_descs);
  802. smartlist_free(chosen_flags);
  803. smartlist_free(versions);
  804. }
  805. /* Add a signature. */
  806. {
  807. char digest[DIGEST_LEN];
  808. char fingerprint[HEX_DIGEST_LEN+1];
  809. char signing_key_fingerprint[HEX_DIGEST_LEN+1];
  810. char buf[4096];
  811. smartlist_add(chunks, tor_strdup("directory-signature "));
  812. /* Compute the hash of the chunks. */
  813. hash_list_members(digest, chunks);
  814. /* Get the fingerprints */
  815. crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
  816. crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
  817. /* add the junk that will go at the end of the line. */
  818. tor_snprintf(buf, sizeof(buf), "%s %s\n", fingerprint,
  819. signing_key_fingerprint);
  820. /* And the signature. */
  821. if (router_append_dirobj_signature(buf, sizeof(buf), digest,
  822. signing_key)) {
  823. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  824. return NULL; /* This leaks, but it should never happen. */
  825. }
  826. smartlist_add(chunks, tor_strdup(buf));
  827. }
  828. result = smartlist_join_strings(chunks, "", 0, NULL);
  829. tor_free(client_versions);
  830. tor_free(server_versions);
  831. smartlist_free(flags);
  832. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  833. smartlist_free(chunks);
  834. {
  835. networkstatus_t *c;
  836. if (!(c = networkstatus_parse_vote_from_string(result, NULL, 0))) {
  837. log_err(LD_BUG,"Generated a networkstatus consensus we couldn't "
  838. "parse.");
  839. tor_free(result);
  840. return NULL;
  841. }
  842. networkstatus_vote_free(c);
  843. }
  844. return result;
  845. }
  846. /** Given a consensus vote <b>target</b> and a set of detached signatures in
  847. * <b>sigs</b> that correspond to the same consensus, check whether there are
  848. * any new signatures in <b>src_voter_list</b> that should be added to
  849. * <b>target. (A signature should be added if we have no signature for that
  850. * voter in <b>target</b> yet, or if we have no verifiable signature and the
  851. * new signature is verifiable.) Return the number of signatures added or
  852. * changed, or -1 if the document signed by <b>sigs</b> isn't the same
  853. * document as <b>target</b>. */
  854. int
  855. networkstatus_add_detached_signatures(networkstatus_t *target,
  856. ns_detached_signatures_t *sigs,
  857. const char **msg_out)
  858. {
  859. int r = 0;
  860. tor_assert(sigs);
  861. tor_assert(target);
  862. tor_assert(!target->is_vote);
  863. /* Do the times seem right? */
  864. if (target->valid_after != sigs->valid_after) {
  865. *msg_out = "Valid-After times do not match "
  866. "when adding detached signatures to consensus";
  867. return -1;
  868. }
  869. if (target->fresh_until != sigs->fresh_until) {
  870. *msg_out = "Fresh-until times do not match "
  871. "when adding detached signatures to consensus";
  872. return -1;
  873. }
  874. if (target->valid_until != sigs->valid_until) {
  875. *msg_out = "Valid-until times do not match "
  876. "when adding detached signatures to consensus";
  877. return -1;
  878. }
  879. /* Are they the same consensus? */
  880. if (memcmp(target->networkstatus_digest, sigs->networkstatus_digest,
  881. DIGEST_LEN)) {
  882. *msg_out = "Digest mismatch when adding detached signatures to consensus";
  883. return -1;
  884. }
  885. /* For each voter in src... */
  886. SMARTLIST_FOREACH(sigs->signatures, networkstatus_voter_info_t *, src_voter,
  887. {
  888. char voter_identity[HEX_DIGEST_LEN+1];
  889. networkstatus_voter_info_t *target_voter =
  890. networkstatus_get_voter_by_id(target, src_voter->identity_digest);
  891. authority_cert_t *cert;
  892. base16_encode(voter_identity, sizeof(voter_identity),
  893. src_voter->identity_digest, DIGEST_LEN);
  894. log_info(LD_DIR, "Looking at signature from %s", voter_identity);
  895. /* If the target doesn't know about this voter, then forget it. */
  896. if (!target_voter) {
  897. log_info(LD_DIR, "We do not know about %s", voter_identity);
  898. continue;
  899. }
  900. /* If the target already has a good signature from this voter, then skip
  901. * this one. */
  902. if (target_voter->good_signature) {
  903. log_info(LD_DIR, "We already have a good signature from %s",
  904. voter_identity);
  905. continue;
  906. }
  907. /* Try checking the signature if we haven't already. */
  908. if (!src_voter->good_signature && !src_voter->bad_signature) {
  909. cert = authority_cert_get_by_digests(src_voter->identity_digest,
  910. src_voter->signing_key_digest);
  911. if (cert) {
  912. networkstatus_check_voter_signature(target, src_voter, cert);
  913. }
  914. }
  915. /* If this signature is good, or we don't have any signature yet,
  916. * then add it. */
  917. if (src_voter->good_signature || !target_voter->signature) {
  918. log_info(LD_DIR, "Adding signature from %s", voter_identity);
  919. ++r;
  920. tor_free(target_voter->signature);
  921. target_voter->signature =
  922. tor_memdup(src_voter->signature, src_voter->signature_len);
  923. memcpy(target_voter->signing_key_digest, src_voter->signing_key_digest,
  924. DIGEST_LEN);
  925. target_voter->signature_len = src_voter->signature_len;
  926. target_voter->good_signature = 1;
  927. target_voter->bad_signature = 0;
  928. } else {
  929. log_info(LD_DIR, "Not adding signature from %s", voter_identity);
  930. }
  931. });
  932. return r;
  933. }
  934. /** Return a newly allocated string holding the detached-signatures document
  935. * corresponding to the signatures on <b>consensus</b>. */
  936. char *
  937. networkstatus_get_detached_signatures(networkstatus_t *consensus)
  938. {
  939. smartlist_t *elements;
  940. char buf[4096];
  941. char *result = NULL;
  942. int n_sigs = 0;
  943. tor_assert(consensus);
  944. tor_assert(! consensus->is_vote);
  945. elements = smartlist_create();
  946. {
  947. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  948. vu_buf[ISO_TIME_LEN+1];
  949. char d[HEX_DIGEST_LEN+1];
  950. base16_encode(d, sizeof(d), consensus->networkstatus_digest, DIGEST_LEN);
  951. format_iso_time(va_buf, consensus->valid_after);
  952. format_iso_time(fu_buf, consensus->fresh_until);
  953. format_iso_time(vu_buf, consensus->valid_until);
  954. tor_snprintf(buf, sizeof(buf),
  955. "consensus-digest %s\n"
  956. "valid-after %s\n"
  957. "fresh-until %s\n"
  958. "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
  959. smartlist_add(elements, tor_strdup(buf));
  960. }
  961. SMARTLIST_FOREACH(consensus->voters, networkstatus_voter_info_t *, v,
  962. {
  963. char sk[HEX_DIGEST_LEN+1];
  964. char id[HEX_DIGEST_LEN+1];
  965. if (!v->signature || v->bad_signature)
  966. continue;
  967. ++n_sigs;
  968. base16_encode(sk, sizeof(sk), v->signing_key_digest, DIGEST_LEN);
  969. base16_encode(id, sizeof(id), v->identity_digest, DIGEST_LEN);
  970. tor_snprintf(buf, sizeof(buf),
  971. "directory-signature %s %s\n-----BEGIN SIGNATURE-----\n",
  972. id, sk);
  973. smartlist_add(elements, tor_strdup(buf));
  974. base64_encode(buf, sizeof(buf), v->signature, v->signature_len);
  975. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  976. smartlist_add(elements, tor_strdup(buf));
  977. });
  978. result = smartlist_join_strings(elements, "", 0, NULL);
  979. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  980. smartlist_free(elements);
  981. if (!n_sigs)
  982. tor_free(result);
  983. return result;
  984. }
  985. /** Release all storage held in <b>s</b>. */
  986. void
  987. ns_detached_signatures_free(ns_detached_signatures_t *s)
  988. {
  989. if (s->signatures) {
  990. SMARTLIST_FOREACH(s->signatures, networkstatus_voter_info_t *, v,
  991. {
  992. tor_free(v->signature);
  993. tor_free(v);
  994. });
  995. smartlist_free(s->signatures);
  996. }
  997. tor_free(s);
  998. }
  999. /* =====
  1000. * Certificate functions
  1001. * ===== */
  1002. /** Allocate and return a new authority_cert_t with the same contents as
  1003. * <b>cert</b>. */
  1004. authority_cert_t *
  1005. authority_cert_dup(authority_cert_t *cert)
  1006. {
  1007. authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
  1008. tor_assert(cert);
  1009. memcpy(out, cert, sizeof(authority_cert_t));
  1010. /* Now copy pointed-to things. */
  1011. out->cache_info.signed_descriptor_body =
  1012. tor_strndup(cert->cache_info.signed_descriptor_body,
  1013. cert->cache_info.signed_descriptor_len);
  1014. out->cache_info.saved_location = SAVED_NOWHERE;
  1015. out->identity_key = crypto_pk_dup_key(cert->identity_key);
  1016. out->signing_key = crypto_pk_dup_key(cert->signing_key);
  1017. return out;
  1018. }
  1019. /* =====
  1020. * Vote scheduling
  1021. * ===== */
  1022. /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
  1023. * Note that these aren't the intervals we'll use to vote; they're the ones
  1024. * that we'll vote to use. */
  1025. void
  1026. dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
  1027. {
  1028. or_options_t *options = get_options();
  1029. tor_assert(timing_out);
  1030. timing_out->vote_interval = options->V3AuthVotingInterval;
  1031. timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
  1032. timing_out->vote_delay = options->V3AuthVoteDelay;
  1033. timing_out->dist_delay = options->V3AuthDistDelay;
  1034. }
  1035. /** Return the start of the next interval of size <b>interval</b> (in seconds)
  1036. * after <b>now</b>. Midnight always starts a fresh interval, and if the last
  1037. * interval of a day would be truncated to less than half its size, it is
  1038. * rolled into the previous interval. */
  1039. time_t
  1040. dirvote_get_start_of_next_interval(time_t now, int interval)
  1041. {
  1042. struct tm tm;
  1043. time_t midnight_today;
  1044. time_t midnight_tomorrow;
  1045. time_t next;
  1046. tor_gmtime_r(&now, &tm);
  1047. tm.tm_hour = 0;
  1048. tm.tm_min = 0;
  1049. tm.tm_sec = 0;
  1050. midnight_today = tor_timegm(&tm);
  1051. midnight_tomorrow = midnight_today + (24*60*60);
  1052. next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
  1053. /* Intervals never cross midnight. */
  1054. if (next > midnight_tomorrow)
  1055. next = midnight_tomorrow;
  1056. /* If the interval would only last half as long as it's supposed to, then
  1057. * skip over to the next day. */
  1058. if (next + interval/2 > midnight_tomorrow)
  1059. next = midnight_tomorrow;
  1060. return next;
  1061. }
  1062. /** Scheduling information for a voting interval. */
  1063. static struct {
  1064. /** When do we generate and distribute our vote for this interval? */
  1065. time_t voting_starts;
  1066. /** When do we send an HTTP request for any votes that we haven't
  1067. * been posted yet?*/
  1068. time_t fetch_missing_votes;
  1069. /** When do we give up on getting more votes and generate a consensus? */
  1070. time_t voting_ends;
  1071. /** When do we send an HTTP request for any signatures we're expecting to
  1072. * see on the consensus? */
  1073. time_t fetch_missing_signatures;
  1074. /** When do we publish the consensus? */
  1075. time_t interval_starts;
  1076. /* True iff we have generated and distributed our vote. */
  1077. int have_voted;
  1078. /* True iff we've requested missing votes. */
  1079. int have_fetched_missing_votes;
  1080. /* True iff we have built a consensus and sent the signatures around. */
  1081. int have_built_consensus;
  1082. /* True iff we've fetched missing signatures. */
  1083. int have_fetched_missing_signatures;
  1084. /* True iff we have published our consensus. */
  1085. int have_published_consensus;
  1086. } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
  1087. /** Set voting_schedule to hold the timing for the next vote we should be
  1088. * doing. */
  1089. void
  1090. dirvote_recalculate_timing(or_options_t *options, time_t now)
  1091. {
  1092. int interval, vote_delay, dist_delay;
  1093. time_t start;
  1094. time_t end;
  1095. networkstatus_t *consensus;
  1096. if (!authdir_mode_v3(options))
  1097. return;
  1098. consensus = networkstatus_get_live_consensus(now);
  1099. memset(&voting_schedule, 0, sizeof(voting_schedule));
  1100. if (consensus) {
  1101. interval = consensus->fresh_until - consensus->valid_after;
  1102. vote_delay = consensus->vote_seconds;
  1103. dist_delay = consensus->dist_seconds;
  1104. } else {
  1105. interval = DEFAULT_VOTING_INTERVAL_WHEN_NO_CONSENSUS;
  1106. vote_delay = dist_delay = 300;
  1107. }
  1108. tor_assert(interval > 0);
  1109. if (vote_delay + dist_delay > interval/2)
  1110. vote_delay = dist_delay = interval / 4;
  1111. start = voting_schedule.interval_starts =
  1112. dirvote_get_start_of_next_interval(now,interval);
  1113. end = dirvote_get_start_of_next_interval(start+1, interval);
  1114. tor_assert(end > start);
  1115. voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
  1116. voting_schedule.voting_ends = start - dist_delay;
  1117. voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
  1118. voting_schedule.voting_starts = start - dist_delay - vote_delay;
  1119. {
  1120. char tbuf[ISO_TIME_LEN+1];
  1121. format_iso_time(tbuf, voting_schedule.interval_starts);
  1122. log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
  1123. "consensus_set=%d, interval=%d",
  1124. tbuf, consensus?1:0, interval);
  1125. }
  1126. }
  1127. /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
  1128. void
  1129. dirvote_act(or_options_t *options, time_t now)
  1130. {
  1131. if (!authdir_mode_v3(options))
  1132. return;
  1133. if (!voting_schedule.voting_starts) {
  1134. char *keys = list_v3_auth_ids();
  1135. authority_cert_t *c = get_my_v3_authority_cert();
  1136. log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
  1137. "Mine is %s.",
  1138. keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
  1139. tor_free(keys);
  1140. dirvote_recalculate_timing(options, now);
  1141. }
  1142. if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
  1143. log_notice(LD_DIR, "Time to vote.");
  1144. dirvote_perform_vote();
  1145. voting_schedule.have_voted = 1;
  1146. }
  1147. if (voting_schedule.fetch_missing_votes < now &&
  1148. !voting_schedule.have_fetched_missing_votes) {
  1149. log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
  1150. dirvote_fetch_missing_votes();
  1151. voting_schedule.have_fetched_missing_votes = 1;
  1152. }
  1153. if (voting_schedule.voting_ends < now &&
  1154. !voting_schedule.have_built_consensus) {
  1155. log_notice(LD_DIR, "Time to compute a consensus.");
  1156. dirvote_compute_consensus();
  1157. /* XXXX We will want to try again later if we haven't got enough
  1158. * votes yet. Implement this if it turns out to ever happen. */
  1159. voting_schedule.have_built_consensus = 1;
  1160. }
  1161. if (voting_schedule.fetch_missing_signatures < now &&
  1162. !voting_schedule.have_fetched_missing_signatures) {
  1163. log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
  1164. dirvote_fetch_missing_signatures();
  1165. voting_schedule.have_fetched_missing_signatures = 1;
  1166. }
  1167. if (voting_schedule.interval_starts < now &&
  1168. !voting_schedule.have_published_consensus) {
  1169. log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
  1170. dirvote_publish_consensus();
  1171. dirvote_clear_votes(0);
  1172. voting_schedule.have_published_consensus = 1;
  1173. /* XXXX We will want to try again later if we haven't got enough
  1174. * signatures yet. Implement this if it turns out to ever happen. */
  1175. dirvote_recalculate_timing(options, now);
  1176. }
  1177. }
  1178. /** A vote networkstatus_t and its unparsed body: held around so we can
  1179. * use it to generate a consensus (at voting_ends) and so we can serve it to
  1180. * other authorities that might want it. */
  1181. typedef struct pending_vote_t {
  1182. cached_dir_t *vote_body;
  1183. networkstatus_t *vote;
  1184. } pending_vote_t;
  1185. /** List of pending_vote_t for the current vote. Before we've used them to
  1186. * build a consensus, the votes go here. */
  1187. static smartlist_t *pending_vote_list = NULL;
  1188. /** List of pending_vote_t for the previous vote. After we've used them to
  1189. * build a consensus, the votes go here for the next period. */
  1190. static smartlist_t *previous_vote_list = NULL;
  1191. /** The body of the consensus that we're currently building. Once we
  1192. * have it built, it goes into dirserv.c */
  1193. static char *pending_consensus_body = NULL;
  1194. /** The detached signatures for the consensus that we're currently
  1195. * building. */
  1196. static char *pending_consensus_signatures = NULL;
  1197. /** The parsed in-progress consensus document. */
  1198. static networkstatus_t *pending_consensus = NULL;
  1199. /** List of ns_detached_signatures_t: hold signatures that get posted to us
  1200. * before we have generated the consensus on our own. */
  1201. static smartlist_t *pending_consensus_signature_list = NULL;
  1202. /** Generate a networkstatus vote and post it to all the v3 authorities.
  1203. * (V3 Authority only) */
  1204. static int
  1205. dirvote_perform_vote(void)
  1206. {
  1207. crypto_pk_env_t *key = get_my_v3_authority_signing_key();
  1208. authority_cert_t *cert = get_my_v3_authority_cert();
  1209. networkstatus_t *ns;
  1210. char *contents;
  1211. pending_vote_t *pending_vote;
  1212. int status;
  1213. const char *msg = "";
  1214. if (!cert || !key) {
  1215. log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
  1216. return -1;
  1217. }
  1218. if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
  1219. return -1;
  1220. contents = format_networkstatus_vote(key, ns);
  1221. networkstatus_vote_free(ns);
  1222. if (!contents)
  1223. return -1;
  1224. pending_vote = dirvote_add_vote(contents, &msg, &status);
  1225. tor_free(contents);
  1226. if (!pending_vote) {
  1227. log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
  1228. msg);
  1229. return -1;
  1230. }
  1231. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
  1232. ROUTER_PURPOSE_GENERAL,
  1233. V3_AUTHORITY,
  1234. pending_vote->vote_body->dir,
  1235. pending_vote->vote_body->dir_len, 0);
  1236. log_notice(LD_DIR, "Vote posted.");
  1237. return 0;
  1238. }
  1239. /** Send an HTTP request to every other v3 authority, for the votes of every
  1240. * authority for which we haven't received a vote yet in this period. (V3
  1241. * authority only) */
  1242. static void
  1243. dirvote_fetch_missing_votes(void)
  1244. {
  1245. smartlist_t *missing_fps = smartlist_create();
  1246. char *resource;
  1247. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1248. trusted_dir_server_t *, ds,
  1249. {
  1250. if (!(ds->type & V3_AUTHORITY))
  1251. continue;
  1252. if (!dirvote_get_vote(ds->v3_identity_digest,
  1253. DGV_BY_ID|DGV_INCLUDE_PENDING)) {
  1254. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  1255. base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
  1256. DIGEST_LEN);
  1257. smartlist_add(missing_fps, cp);
  1258. }
  1259. });
  1260. if (!smartlist_len(missing_fps)) {
  1261. smartlist_free(missing_fps);
  1262. return;
  1263. }
  1264. log_notice(LOG_NOTICE, "We're missing votes from %d authorities. Asking "
  1265. "every other authority for a copy.", smartlist_len(missing_fps));
  1266. resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
  1267. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
  1268. 0, resource);
  1269. tor_free(resource);
  1270. SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
  1271. smartlist_free(missing_fps);
  1272. }
  1273. /** Send a request to every other authority for its detached signatures,
  1274. * unless we have signatures from all other v3 authorities already. */
  1275. static void
  1276. dirvote_fetch_missing_signatures(void)
  1277. {
  1278. if (!pending_consensus)
  1279. return;
  1280. if (networkstatus_check_consensus_signature(pending_consensus, -1) == 1)
  1281. return; /* we have a signature from everybody. */
  1282. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
  1283. 0, NULL);
  1284. }
  1285. /** Drop all currently pending votes, consensus, and detached signatures. */
  1286. static void
  1287. dirvote_clear_votes(int all_votes)
  1288. {
  1289. if (!previous_vote_list)
  1290. previous_vote_list = smartlist_create();
  1291. if (!pending_vote_list)
  1292. pending_vote_list = smartlist_create();
  1293. /* All "previous" votes are now junk. */
  1294. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
  1295. cached_dir_decref(v->vote_body);
  1296. v->vote_body = NULL;
  1297. networkstatus_vote_free(v->vote);
  1298. tor_free(v);
  1299. });
  1300. smartlist_clear(previous_vote_list);
  1301. if (all_votes) {
  1302. /* If we're dumping all the votes, we delete the pending ones. */
  1303. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1304. cached_dir_decref(v->vote_body);
  1305. v->vote_body = NULL;
  1306. networkstatus_vote_free(v->vote);
  1307. tor_free(v);
  1308. });
  1309. } else {
  1310. /* Otherwise, we move them into "previous". */
  1311. smartlist_add_all(previous_vote_list, pending_vote_list);
  1312. }
  1313. smartlist_clear(pending_vote_list);
  1314. if (pending_consensus_signature_list) {
  1315. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
  1316. tor_free(cp));
  1317. smartlist_clear(pending_consensus_signature_list);
  1318. }
  1319. tor_free(pending_consensus_body);
  1320. tor_free(pending_consensus_signatures);
  1321. if (pending_consensus) {
  1322. networkstatus_vote_free(pending_consensus);
  1323. pending_consensus = NULL;
  1324. }
  1325. }
  1326. /** Return a newly allocated string containing the hex-encoded v3 authority
  1327. identity digest of every recognized v3 authority. */
  1328. static char *
  1329. list_v3_auth_ids(void)
  1330. {
  1331. smartlist_t *known_v3_keys = smartlist_create();
  1332. char *keys;
  1333. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1334. trusted_dir_server_t *, ds,
  1335. if ((ds->type & V3_AUTHORITY) &&
  1336. !tor_digest_is_zero(ds->v3_identity_digest))
  1337. smartlist_add(known_v3_keys,
  1338. tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
  1339. keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
  1340. SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
  1341. smartlist_free(known_v3_keys);
  1342. return keys;
  1343. }
  1344. /** Called when we have received a networkstatus vote in <b>vote_body</b>.
  1345. * Parse and validate it, and on success store it as a pending vote (which we
  1346. * then return). Return NULL on failure. Sets *<b>msg_out</b> and
  1347. * *<b>status_out</b> to an HTTP response and status code. (V3 authority
  1348. * only) */
  1349. pending_vote_t *
  1350. dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
  1351. {
  1352. networkstatus_t *vote;
  1353. networkstatus_voter_info_t *vi;
  1354. trusted_dir_server_t *ds;
  1355. pending_vote_t *pending_vote = NULL;
  1356. const char *end_of_vote = NULL;
  1357. int any_failed = 0;
  1358. tor_assert(vote_body);
  1359. tor_assert(msg_out);
  1360. tor_assert(status_out);
  1361. if (!pending_vote_list)
  1362. pending_vote_list = smartlist_create();
  1363. *status_out = 0;
  1364. *msg_out = NULL;
  1365. again:
  1366. vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote, 1);
  1367. if (!end_of_vote)
  1368. end_of_vote = vote_body + strlen(vote_body);
  1369. if (!vote) {
  1370. log_warn(LD_DIR, "Couldn't parse vote: length was %d",
  1371. (int)strlen(vote_body));
  1372. *msg_out = "Unable to parse vote";
  1373. goto err;
  1374. }
  1375. tor_assert(smartlist_len(vote->voters) == 1);
  1376. vi = get_voter(vote);
  1377. tor_assert(vi->good_signature == 1);
  1378. ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
  1379. if (!ds) {
  1380. char *keys = list_v3_auth_ids();
  1381. log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
  1382. "with authority key ID %s. "
  1383. "This key ID is not recognized. Known v3 key IDs are: %s",
  1384. vi->nickname, vi->address,
  1385. hex_str(vi->identity_digest, DIGEST_LEN), keys);
  1386. tor_free(keys);
  1387. *msg_out = "Vote not from a recognized v3 authority";
  1388. goto err;
  1389. }
  1390. tor_assert(vote->cert);
  1391. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1392. vote->cert->signing_key_digest)) {
  1393. /* Hey, it's a new cert! */
  1394. trusted_dirs_load_certs_from_string(
  1395. vote->cert->cache_info.signed_descriptor_body,
  1396. 0 /* from_store */);
  1397. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1398. vote->cert->signing_key_digest)) {
  1399. log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
  1400. }
  1401. }
  1402. /* Is it for the right period? */
  1403. if (vote->valid_after != voting_schedule.interval_starts) {
  1404. char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
  1405. format_iso_time(tbuf1, vote->valid_after);
  1406. format_iso_time(tbuf2, voting_schedule.interval_starts);
  1407. log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
  1408. "we were expecting %s", vi->address, tbuf1, tbuf2);
  1409. *msg_out = "Bad valid-after time";
  1410. goto err;
  1411. }
  1412. /* Now see whether we already h<ave a vote from this authority.*/
  1413. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1414. if (! memcmp(v->vote->cert->cache_info.identity_digest,
  1415. vote->cert->cache_info.identity_digest,
  1416. DIGEST_LEN)) {
  1417. networkstatus_voter_info_t *vi_old = get_voter(v->vote);
  1418. if (!memcmp(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
  1419. /* Ah, it's the same vote. Not a problem. */
  1420. log_info(LD_DIR, "Discarding a vote we already have.");
  1421. if (*status_out < 200)
  1422. *status_out = 200;
  1423. goto discard;
  1424. } else if (v->vote->published < vote->published) {
  1425. log_notice(LD_DIR, "Replacing an older pending vote from this "
  1426. "directory.");
  1427. cached_dir_decref(v->vote_body);
  1428. networkstatus_vote_free(v->vote);
  1429. v->vote_body = new_cached_dir(tor_strndup(vote_body,
  1430. end_of_vote-vote_body),
  1431. vote->published);
  1432. v->vote = vote;
  1433. if (end_of_vote &&
  1434. !strcmpstart(end_of_vote, "network-status-version"))
  1435. goto again;
  1436. if (*status_out < 200)
  1437. *status_out = 200;
  1438. if (!*msg_out)
  1439. *msg_out = "OK";
  1440. return v;
  1441. } else {
  1442. *msg_out = "Already have a newer pending vote";
  1443. goto err;
  1444. }
  1445. }
  1446. });
  1447. pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
  1448. pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
  1449. end_of_vote-vote_body),
  1450. vote->published);
  1451. pending_vote->vote = vote;
  1452. smartlist_add(pending_vote_list, pending_vote);
  1453. if (!strcmpstart(end_of_vote, "network-status-version ")) {
  1454. vote_body = end_of_vote;
  1455. goto again;
  1456. }
  1457. goto done;
  1458. err:
  1459. any_failed = 1;
  1460. if (!*msg_out)
  1461. *msg_out = "Error adding vote";
  1462. if (*status_out < 400)
  1463. *status_out = 400;
  1464. discard:
  1465. if (vote)
  1466. networkstatus_vote_free(vote);
  1467. if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
  1468. vote_body = end_of_vote;
  1469. goto again;
  1470. }
  1471. done:
  1472. if (*status_out < 200)
  1473. *status_out = 200;
  1474. if (!*msg_out) {
  1475. if (!any_failed && !pending_vote) {
  1476. *msg_out = "Duplicate discarded";
  1477. } else {
  1478. *msg_out = "ok";
  1479. }
  1480. }
  1481. return any_failed ? NULL : pending_vote;
  1482. }
  1483. /** Try to compute a v3 networkstatus consensus from the currently pending
  1484. * votes. Return 0 on success, -1 on failure. Store the consensus in
  1485. * pending_consensus: it won't be ready to be published until we have
  1486. * everybody else's signatures collected too. (V3 Authoritity only) */
  1487. static int
  1488. dirvote_compute_consensus(void)
  1489. {
  1490. /* Have we got enough votes to try? */
  1491. int n_votes, n_voters;
  1492. smartlist_t *votes = NULL;
  1493. char *consensus_body = NULL, *signatures = NULL;
  1494. networkstatus_t *consensus = NULL;
  1495. authority_cert_t *my_cert;
  1496. if (!pending_vote_list)
  1497. pending_vote_list = smartlist_create();
  1498. n_voters = get_n_authorities(V3_AUTHORITY);
  1499. n_votes = smartlist_len(pending_vote_list);
  1500. if (n_votes <= n_voters/2) {
  1501. log_warn(LD_DIR, "We don't have enough votes to generate a consensus.");
  1502. goto err;
  1503. }
  1504. if (!(my_cert = get_my_v3_authority_cert())) {
  1505. log_warn(LD_DIR, "Can't generate consensus without a certificate.");
  1506. goto err;
  1507. }
  1508. votes = smartlist_create();
  1509. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
  1510. smartlist_add(votes, v->vote));
  1511. consensus_body = networkstatus_compute_consensus(
  1512. votes, n_voters,
  1513. my_cert->identity_key,
  1514. get_my_v3_authority_signing_key());
  1515. if (!consensus_body) {
  1516. log_warn(LD_DIR, "Couldn't generate a consensus at all!");
  1517. goto err;
  1518. }
  1519. consensus = networkstatus_parse_vote_from_string(consensus_body, NULL, 0);
  1520. if (!consensus) {
  1521. log_warn(LD_DIR, "Couldn't parse consensus we generated!");
  1522. goto err;
  1523. }
  1524. /* 'Check' our own signature, to mark it valid. */
  1525. networkstatus_check_consensus_signature(consensus, -1);
  1526. signatures = networkstatus_get_detached_signatures(consensus);
  1527. if (!signatures) {
  1528. log_warn(LD_DIR, "Couldn't extract signatures.");
  1529. goto err;
  1530. }
  1531. tor_free(pending_consensus_body);
  1532. pending_consensus_body = consensus_body;
  1533. tor_free(pending_consensus_signatures);
  1534. pending_consensus_signatures = signatures;
  1535. if (pending_consensus)
  1536. networkstatus_vote_free(pending_consensus);
  1537. pending_consensus = consensus;
  1538. if (pending_consensus_signature_list) {
  1539. int n_sigs = 0;
  1540. /* we may have gotten signatures for this consensus before we built
  1541. * it ourself. Add them now. */
  1542. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, sig,
  1543. {
  1544. const char *msg = NULL;
  1545. int r = dirvote_add_signatures_to_pending_consensus(sig, &msg);
  1546. if (r >= 0)
  1547. n_sigs += r;
  1548. else
  1549. log_warn(LD_DIR,
  1550. "Could not add queued signature to new consensus: %s",
  1551. msg);
  1552. tor_free(sig);
  1553. });
  1554. if (n_sigs)
  1555. log_notice(LD_DIR, "Added %d pending signatures while building "
  1556. "consensus.", n_sigs);
  1557. smartlist_clear(pending_consensus_signature_list);
  1558. }
  1559. log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
  1560. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
  1561. ROUTER_PURPOSE_GENERAL,
  1562. V3_AUTHORITY,
  1563. pending_consensus_signatures,
  1564. strlen(pending_consensus_signatures), 0);
  1565. log_notice(LD_DIR, "Signature(s) posted.");
  1566. return 0;
  1567. err:
  1568. if (votes)
  1569. smartlist_free(votes);
  1570. tor_free(consensus_body);
  1571. tor_free(signatures);
  1572. networkstatus_vote_free(consensus);
  1573. return -1;
  1574. }
  1575. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  1576. * signatures on the currently pending consensus. Add them to the consensus
  1577. * as appropriate. Return the number of signatures added. (?) */
  1578. static int
  1579. dirvote_add_signatures_to_pending_consensus(
  1580. const char *detached_signatures_body,
  1581. const char **msg_out)
  1582. {
  1583. ns_detached_signatures_t *sigs = NULL;
  1584. int r = -1;
  1585. tor_assert(detached_signatures_body);
  1586. tor_assert(msg_out);
  1587. /* Only call if we have a pending consensus right now. */
  1588. tor_assert(pending_consensus);
  1589. tor_assert(pending_consensus_body);
  1590. tor_assert(pending_consensus_signatures);
  1591. *msg_out = NULL;
  1592. if (!(sigs = networkstatus_parse_detached_signatures(
  1593. detached_signatures_body, NULL))) {
  1594. *msg_out = "Couldn't parse detached signatures.";
  1595. goto err;
  1596. }
  1597. log_info(LD_DIR, "Have %d signatures for adding to consensus.",
  1598. smartlist_len(sigs->signatures));
  1599. r = networkstatus_add_detached_signatures(pending_consensus,
  1600. sigs, msg_out);
  1601. log_info(LD_DIR,"Added %d signatures to consensus.", r);
  1602. if (r >= 0) {
  1603. char *new_detached =
  1604. networkstatus_get_detached_signatures(pending_consensus);
  1605. const char *src;
  1606. char *dst;
  1607. size_t new_consensus_len =
  1608. strlen(pending_consensus_body) + strlen(new_detached) + 1;
  1609. pending_consensus_body = tor_realloc(pending_consensus_body,
  1610. new_consensus_len);
  1611. dst = strstr(pending_consensus_body, "directory-signature ");
  1612. tor_assert(dst);
  1613. src = strstr(new_detached, "directory-signature ");
  1614. tor_assert(src);
  1615. strlcpy(dst, src, new_consensus_len - (dst-pending_consensus_body));
  1616. /* We remove this block once it has failed to crash for a while. But
  1617. * unless it shows up in profiles, we're probably better leaving it in,
  1618. * just in case we break detached signature processing at some point. */
  1619. {
  1620. ns_detached_signatures_t *sigs =
  1621. networkstatus_parse_detached_signatures(new_detached, NULL);
  1622. networkstatus_t *v = networkstatus_parse_vote_from_string(
  1623. pending_consensus_body, NULL, 0);
  1624. tor_assert(sigs);
  1625. ns_detached_signatures_free(sigs);
  1626. tor_assert(v);
  1627. networkstatus_vote_free(v);
  1628. }
  1629. tor_free(pending_consensus_signatures);
  1630. pending_consensus_signatures = new_detached;
  1631. *msg_out = "Signatures added";
  1632. } else {
  1633. goto err;
  1634. }
  1635. goto done;
  1636. err:
  1637. if (!msg_out)
  1638. *msg_out = "Unrecognized error while adding detached signatures.";
  1639. done:
  1640. if (sigs)
  1641. ns_detached_signatures_free(sigs);
  1642. return r;
  1643. }
  1644. /** Helper: we just got the <b>deteached_signatures_body</b> sent to us as
  1645. * signatures on the currently pending consensus. Add them to the pending
  1646. * consensus (if we have one); otherwise queue them until we have a
  1647. * consensus. Return negative on failure, nonnegative on success. */
  1648. int
  1649. dirvote_add_signatures(const char *detached_signatures_body,
  1650. const char *source,
  1651. const char **msg)
  1652. {
  1653. if (pending_consensus) {
  1654. log_notice(LD_DIR, "Got a signature from %s. "
  1655. "Adding it to the pending consensus.", source);
  1656. return dirvote_add_signatures_to_pending_consensus(
  1657. detached_signatures_body, msg);
  1658. } else {
  1659. log_notice(LD_DIR, "Got a signature from %s. "
  1660. "Queueing it for the next consensus.", source);
  1661. if (!pending_consensus_signature_list)
  1662. pending_consensus_signature_list = smartlist_create();
  1663. smartlist_add(pending_consensus_signature_list,
  1664. tor_strdup(detached_signatures_body));
  1665. *msg = "Signature queued";
  1666. return 0;
  1667. }
  1668. }
  1669. /** Replace the consensus that we're currently serving with the one that we've
  1670. * been building. (V3 Authority only) */
  1671. static int
  1672. dirvote_publish_consensus(void)
  1673. {
  1674. /* Can we actually publish it yet? */
  1675. if (!pending_consensus ||
  1676. networkstatus_check_consensus_signature(pending_consensus, 1)<0) {
  1677. log_warn(LD_DIR, "Not enough info to publish pending consensus");
  1678. return -1;
  1679. }
  1680. if (networkstatus_set_current_consensus(pending_consensus_body, 0))
  1681. log_warn(LD_DIR, "Error publishing consensus");
  1682. else
  1683. log_notice(LD_DIR, "Consensus published.");
  1684. return 0;
  1685. }
  1686. /** Release all static storage held in dirvote.c */
  1687. void
  1688. dirvote_free_all(void)
  1689. {
  1690. dirvote_clear_votes(1);
  1691. /* now empty as a result of clear_pending_votes. */
  1692. smartlist_free(pending_vote_list);
  1693. pending_vote_list = NULL;
  1694. smartlist_free(previous_vote_list);
  1695. previous_vote_list = NULL;
  1696. tor_free(pending_consensus_body);
  1697. tor_free(pending_consensus_signatures);
  1698. if (pending_consensus) {
  1699. networkstatus_vote_free(pending_consensus);
  1700. pending_consensus = NULL;
  1701. }
  1702. if (pending_consensus_signature_list) {
  1703. /* now empty as a result of clear_pending_votes. */
  1704. smartlist_free(pending_consensus_signature_list);
  1705. pending_consensus_signature_list = NULL;
  1706. }
  1707. }
  1708. /* ====
  1709. * Access to pending items.
  1710. * ==== */
  1711. /** Return the body of the consensus that we're currently trying to build. */
  1712. const char *
  1713. dirvote_get_pending_consensus(void)
  1714. {
  1715. return pending_consensus_body;
  1716. }
  1717. /** Return the signatures that we know for the consensus that we're currently
  1718. * trying to build */
  1719. const char *
  1720. dirvote_get_pending_detached_signatures(void)
  1721. {
  1722. return pending_consensus_signatures;
  1723. }
  1724. /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
  1725. * vote for the authority with the v3 authority identity key digest <b>fp</b>;
  1726. * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
  1727. * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
  1728. * false, do not consider any votes for a consensus that's already been built.
  1729. * If <b>include_pending</b> is false, do not consider any votes for the
  1730. * consensus that's in progress. May return NULL if we have no vote for the
  1731. * authority in question. */
  1732. const cached_dir_t *
  1733. dirvote_get_vote(const char *fp, int flags)
  1734. {
  1735. int by_id = flags & DGV_BY_ID;
  1736. const int include_pending = flags & DGV_INCLUDE_PENDING;
  1737. const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
  1738. if (!pending_vote_list && !previous_vote_list)
  1739. return NULL;
  1740. if (fp == NULL) {
  1741. authority_cert_t *c = get_my_v3_authority_cert();
  1742. if (c) {
  1743. fp = c->cache_info.identity_digest;
  1744. by_id = 1;
  1745. } else
  1746. return NULL;
  1747. }
  1748. if (by_id) {
  1749. if (pending_vote_list && include_pending) {
  1750. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  1751. if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  1752. return pv->vote_body);
  1753. }
  1754. if (previous_vote_list && include_previous) {
  1755. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  1756. if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  1757. return pv->vote_body);
  1758. }
  1759. } else {
  1760. if (pending_vote_list && include_pending) {
  1761. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  1762. if (!memcmp(pv->vote->networkstatus_digest, fp, DIGEST_LEN))
  1763. return pv->vote_body);
  1764. }
  1765. if (previous_vote_list && include_previous) {
  1766. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  1767. if (!memcmp(pv->vote->networkstatus_digest, fp, DIGEST_LEN))
  1768. return pv->vote_body);
  1769. }
  1770. }
  1771. return NULL;
  1772. }