dirvote.c 65 KB

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