dirvote.c 98 KB

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