dirvote.c 65 KB

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