dirvote.c 66 KB

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