dirvote.c 65 KB

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