dirvote.c 82 KB

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