dirvote.c 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861
  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=NULL;
  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_asprintf(&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, buf);
  706. if (consensus_method >= 2) {
  707. tor_asprintf(&buf, "consensus-method %d\n",
  708. consensus_method);
  709. smartlist_add(chunks, buf);
  710. }
  711. tor_asprintf(&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, 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_BEGIN(dir_sources, const dir_src_ent_t *, e) {
  755. struct in_addr in;
  756. char ip[INET_NTOA_BUF_LEN];
  757. char fingerprint[HEX_DIGEST_LEN+1];
  758. char votedigest[HEX_DIGEST_LEN+1];
  759. networkstatus_t *v = e->v;
  760. networkstatus_voter_info_t *voter = get_voter(v);
  761. char *buf = NULL;
  762. if (e->is_legacy)
  763. tor_assert(consensus_method >= 2);
  764. in.s_addr = htonl(voter->addr);
  765. tor_inet_ntoa(&in, ip, sizeof(ip));
  766. base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
  767. base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
  768. DIGEST_LEN);
  769. tor_asprintf(&buf,
  770. "dir-source %s%s %s %s %s %d %d\n",
  771. voter->nickname, e->is_legacy ? "-legacy" : "",
  772. fingerprint, voter->address, ip,
  773. voter->dir_port,
  774. voter->or_port);
  775. smartlist_add(chunks, buf);
  776. if (! e->is_legacy) {
  777. tor_asprintf(&buf,
  778. "contact %s\n"
  779. "vote-digest %s\n",
  780. voter->contact,
  781. votedigest);
  782. smartlist_add(chunks, buf);
  783. }
  784. } SMARTLIST_FOREACH_END(e);
  785. SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
  786. smartlist_free(dir_sources);
  787. }
  788. /* Add the actual router entries. */
  789. {
  790. int *index; /* index[j] is the current index into votes[j]. */
  791. int *size; /* size[j] is the number of routerstatuses in votes[j]. */
  792. int *flag_counts; /* The number of voters that list flag[j] for the
  793. * currently considered router. */
  794. int i;
  795. smartlist_t *matching_descs = smartlist_create();
  796. smartlist_t *chosen_flags = smartlist_create();
  797. smartlist_t *versions = smartlist_create();
  798. smartlist_t *exitsummaries = smartlist_create();
  799. uint32_t *bandwidths = tor_malloc(sizeof(uint32_t) * smartlist_len(votes));
  800. uint32_t *measured_bws = tor_malloc(sizeof(uint32_t) *
  801. smartlist_len(votes));
  802. int num_bandwidths;
  803. int num_mbws;
  804. int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
  805. * votes[j] knows about. */
  806. int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
  807. * about flags[f]. */
  808. int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
  809. * is the same flag as votes[j]->known_flags[b]. */
  810. int *named_flag; /* Index of the flag "Named" for votes[j] */
  811. int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
  812. int chosen_named_idx, chosen_unnamed_idx;
  813. strmap_t *name_to_id_map = strmap_new();
  814. char conflict[DIGEST_LEN];
  815. char unknown[DIGEST_LEN];
  816. memset(conflict, 0, sizeof(conflict));
  817. memset(unknown, 0xff, sizeof(conflict));
  818. index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  819. size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  820. n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  821. n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
  822. flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  823. named_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  824. unnamed_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  825. for (i = 0; i < smartlist_len(votes); ++i)
  826. unnamed_flag[i] = named_flag[i] = -1;
  827. chosen_named_idx = smartlist_string_pos(flags, "Named");
  828. chosen_unnamed_idx = smartlist_string_pos(flags, "Unnamed");
  829. /* Build the flag index. */
  830. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  831. {
  832. flag_map[v_sl_idx] = tor_malloc_zero(
  833. sizeof(int)*smartlist_len(v->known_flags));
  834. SMARTLIST_FOREACH(v->known_flags, const char *, fl,
  835. {
  836. int p = smartlist_string_pos(flags, fl);
  837. tor_assert(p >= 0);
  838. flag_map[v_sl_idx][fl_sl_idx] = p;
  839. ++n_flag_voters[p];
  840. if (!strcmp(fl, "Named"))
  841. named_flag[v_sl_idx] = fl_sl_idx;
  842. if (!strcmp(fl, "Unnamed"))
  843. unnamed_flag[v_sl_idx] = fl_sl_idx;
  844. });
  845. n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
  846. size[v_sl_idx] = smartlist_len(v->routerstatus_list);
  847. });
  848. /* Named and Unnamed get treated specially */
  849. if (consensus_method >= 2) {
  850. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  851. {
  852. uint64_t nf;
  853. if (named_flag[v_sl_idx]<0)
  854. continue;
  855. nf = U64_LITERAL(1) << named_flag[v_sl_idx];
  856. SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
  857. {
  858. if ((rs->flags & nf) != 0) {
  859. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  860. if (!d) {
  861. /* We have no name officially mapped to this digest. */
  862. strmap_set_lc(name_to_id_map, rs->status.nickname,
  863. rs->status.identity_digest);
  864. } else if (d != conflict &&
  865. memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  866. /* Authorities disagree about this nickname. */
  867. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  868. } else {
  869. /* It's already a conflict, or it's already this ID. */
  870. }
  871. }
  872. });
  873. });
  874. SMARTLIST_FOREACH(votes, networkstatus_t *, v,
  875. {
  876. uint64_t uf;
  877. if (unnamed_flag[v_sl_idx]<0)
  878. continue;
  879. uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
  880. SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
  881. {
  882. if ((rs->flags & uf) != 0) {
  883. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  884. if (d == conflict || d == unknown) {
  885. /* Leave it alone; we know what it is. */
  886. } else if (!d) {
  887. /* We have no name officially mapped to this digest. */
  888. strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
  889. } else if (!memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  890. /* Authorities disagree about this nickname. */
  891. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  892. } else {
  893. /* It's mapped to a different name. */
  894. }
  895. }
  896. });
  897. });
  898. }
  899. /* Now go through all the votes */
  900. flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
  901. while (1) {
  902. vote_routerstatus_t *rs;
  903. routerstatus_t rs_out;
  904. const char *lowest_id = NULL;
  905. const char *chosen_version;
  906. const char *chosen_name = NULL;
  907. int exitsummary_disagreement = 0;
  908. int is_named = 0, is_unnamed = 0, is_running = 0;
  909. int naming_conflict = 0;
  910. int n_listing = 0;
  911. int i;
  912. char *buf=NULL;
  913. char microdesc_digest[DIGEST256_LEN];
  914. /* Of the next-to-be-considered digest in each voter, which is first? */
  915. SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
  916. if (index[v_sl_idx] < size[v_sl_idx]) {
  917. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  918. if (!lowest_id ||
  919. memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN) < 0)
  920. lowest_id = rs->status.identity_digest;
  921. }
  922. });
  923. if (!lowest_id) /* we're out of routers. */
  924. break;
  925. memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
  926. smartlist_clear(matching_descs);
  927. smartlist_clear(chosen_flags);
  928. smartlist_clear(versions);
  929. num_bandwidths = 0;
  930. num_mbws = 0;
  931. /* Okay, go through all the entries for this digest. */
  932. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  933. if (index[v_sl_idx] >= size[v_sl_idx])
  934. continue; /* out of entries. */
  935. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  936. if (memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
  937. continue; /* doesn't include this router. */
  938. /* At this point, we know that we're looking at a routerstatus with
  939. * identity "lowest".
  940. */
  941. ++index[v_sl_idx];
  942. ++n_listing;
  943. smartlist_add(matching_descs, rs);
  944. if (rs->version && rs->version[0])
  945. smartlist_add(versions, rs->version);
  946. /* Tally up all the flags. */
  947. for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
  948. if (rs->flags & (U64_LITERAL(1) << i))
  949. ++flag_counts[flag_map[v_sl_idx][i]];
  950. }
  951. if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
  952. if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
  953. log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
  954. chosen_name, rs->status.nickname);
  955. naming_conflict = 1;
  956. }
  957. chosen_name = rs->status.nickname;
  958. }
  959. /* count bandwidths */
  960. if (rs->status.has_measured_bw)
  961. measured_bws[num_mbws++] = rs->status.measured_bw;
  962. if (rs->status.has_bandwidth)
  963. bandwidths[num_bandwidths++] = rs->status.bandwidth;
  964. } SMARTLIST_FOREACH_END(v);
  965. /* We don't include this router at all unless more than half of
  966. * the authorities we believe in list it. */
  967. if (n_listing <= total_authorities/2)
  968. continue;
  969. /* Figure out the most popular opinion of what the most recent
  970. * routerinfo and its contents are. */
  971. memset(microdesc_digest, 0, sizeof(microdesc_digest));
  972. rs = compute_routerstatus_consensus(matching_descs, consensus_method,
  973. microdesc_digest);
  974. /* Copy bits of that into rs_out. */
  975. tor_assert(!memcmp(lowest_id, rs->status.identity_digest, DIGEST_LEN));
  976. memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
  977. memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
  978. DIGEST_LEN);
  979. rs_out.addr = rs->status.addr;
  980. rs_out.published_on = rs->status.published_on;
  981. rs_out.dir_port = rs->status.dir_port;
  982. rs_out.or_port = rs->status.or_port;
  983. rs_out.has_bandwidth = 0;
  984. rs_out.has_exitsummary = 0;
  985. if (chosen_name && !naming_conflict) {
  986. strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
  987. } else {
  988. strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
  989. }
  990. if (consensus_method == 1) {
  991. is_named = chosen_named_idx >= 0 &&
  992. (!naming_conflict && flag_counts[chosen_named_idx]);
  993. } else {
  994. const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
  995. if (!d) {
  996. is_named = is_unnamed = 0;
  997. } else if (!memcmp(d, lowest_id, DIGEST_LEN)) {
  998. is_named = 1; is_unnamed = 0;
  999. } else {
  1000. is_named = 0; is_unnamed = 1;
  1001. }
  1002. }
  1003. /* Set the flags. */
  1004. smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
  1005. SMARTLIST_FOREACH(flags, const char *, fl,
  1006. {
  1007. if (!strcmp(fl, "Named")) {
  1008. if (is_named)
  1009. smartlist_add(chosen_flags, (char*)fl);
  1010. } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
  1011. if (is_unnamed)
  1012. smartlist_add(chosen_flags, (char*)fl);
  1013. } else {
  1014. if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
  1015. smartlist_add(chosen_flags, (char*)fl);
  1016. if (!strcmp(fl, "Running"))
  1017. is_running = 1;
  1018. }
  1019. }
  1020. });
  1021. /* Starting with consensus method 4 we do not list servers
  1022. * that are not running in a consensus. See Proposal 138 */
  1023. if (consensus_method >= 4 && !is_running)
  1024. continue;
  1025. /* Pick the version. */
  1026. if (smartlist_len(versions)) {
  1027. sort_version_list(versions, 0);
  1028. chosen_version = get_most_frequent_member(versions);
  1029. } else {
  1030. chosen_version = NULL;
  1031. }
  1032. /* Pick a bandwidth */
  1033. if (consensus_method >= 6 && num_mbws > 2) {
  1034. rs_out.has_bandwidth = 1;
  1035. rs_out.bandwidth = median_uint32(measured_bws, num_mbws);
  1036. } else if (consensus_method >= 5 && num_bandwidths > 0) {
  1037. rs_out.has_bandwidth = 1;
  1038. rs_out.bandwidth = median_uint32(bandwidths, num_bandwidths);
  1039. }
  1040. /* Ok, we already picked a descriptor digest we want to list
  1041. * previously. Now we want to use the exit policy summary from
  1042. * that descriptor. If everybody plays nice all the voters who
  1043. * listed that descriptor will have the same summary. If not then
  1044. * something is fishy and we'll use the most common one (breaking
  1045. * ties in favor of lexicographically larger one (only because it
  1046. * lets me reuse more existing code.
  1047. *
  1048. * The other case that can happen is that no authority that voted
  1049. * for that descriptor has an exit policy summary. That's
  1050. * probably quite unlikely but can happen. In that case we use
  1051. * the policy that was most often listed in votes, again breaking
  1052. * ties like in the previous case.
  1053. */
  1054. if (consensus_method >= 5) {
  1055. /* Okay, go through all the votes for this router. We prepared
  1056. * that list previously */
  1057. const char *chosen_exitsummary = NULL;
  1058. smartlist_clear(exitsummaries);
  1059. SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
  1060. /* Check if the vote where this status comes from had the
  1061. * proper descriptor */
  1062. tor_assert(!memcmp(rs_out.identity_digest,
  1063. vsr->status.identity_digest,
  1064. DIGEST_LEN));
  1065. if (vsr->status.has_exitsummary &&
  1066. !memcmp(rs_out.descriptor_digest,
  1067. vsr->status.descriptor_digest,
  1068. DIGEST_LEN)) {
  1069. tor_assert(vsr->status.exitsummary);
  1070. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1071. if (!chosen_exitsummary) {
  1072. chosen_exitsummary = vsr->status.exitsummary;
  1073. } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
  1074. /* Great. There's disagreement among the voters. That
  1075. * really shouldn't be */
  1076. exitsummary_disagreement = 1;
  1077. }
  1078. }
  1079. });
  1080. if (exitsummary_disagreement) {
  1081. char id[HEX_DIGEST_LEN+1];
  1082. char dd[HEX_DIGEST_LEN+1];
  1083. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1084. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1085. log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
  1086. " for router %s with descriptor %s. This really shouldn't"
  1087. " have happened.", id, dd);
  1088. smartlist_sort_strings(exitsummaries);
  1089. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1090. } else if (!chosen_exitsummary) {
  1091. char id[HEX_DIGEST_LEN+1];
  1092. char dd[HEX_DIGEST_LEN+1];
  1093. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1094. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1095. log_warn(LD_DIR, "Not one of the voters that made us select"
  1096. "descriptor %s for router %s had an exit policy"
  1097. "summary", dd, id);
  1098. /* Ok, none of those voting for the digest we chose had an
  1099. * exit policy for us. Well, that kinda sucks.
  1100. */
  1101. smartlist_clear(exitsummaries);
  1102. SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
  1103. if (vsr->status.has_exitsummary)
  1104. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1105. });
  1106. smartlist_sort_strings(exitsummaries);
  1107. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1108. if (!chosen_exitsummary)
  1109. log_warn(LD_DIR, "Wow, not one of the voters had an exit "
  1110. "policy summary for %s. Wow.", id);
  1111. }
  1112. if (chosen_exitsummary) {
  1113. rs_out.has_exitsummary = 1;
  1114. /* yea, discards the const */
  1115. rs_out.exitsummary = (char *)chosen_exitsummary;
  1116. }
  1117. }
  1118. {
  1119. char buf[4096];
  1120. /* Okay!! Now we can write the descriptor... */
  1121. /* First line goes into "buf". */
  1122. routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL,
  1123. rs_format);
  1124. smartlist_add(chunks, tor_strdup(buf));
  1125. }
  1126. /* Now an m line, if applicable. */
  1127. if (flavor == FLAV_MICRODESC &&
  1128. !tor_digest256_is_zero(microdesc_digest)) {
  1129. char m[BASE64_DIGEST256_LEN+1], *cp;
  1130. digest256_to_base64(m, microdesc_digest);
  1131. tor_asprintf(&cp, "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. char *cp=NULL;
  1146. tor_asprintf(&cp, "w Bandwidth=%d\n", rs_out.bandwidth);
  1147. smartlist_add(chunks, cp);
  1148. }
  1149. /* Now the exitpolicy summary line. */
  1150. if (rs_out.has_exitsummary && flavor == FLAV_NS) {
  1151. tor_asprintf(&buf, "p %s\n", rs_out.exitsummary);
  1152. smartlist_add(chunks, buf);
  1153. }
  1154. /* And the loop is over and we move on to the next router */
  1155. }
  1156. tor_free(index);
  1157. tor_free(size);
  1158. tor_free(n_voter_flags);
  1159. tor_free(n_flag_voters);
  1160. for (i = 0; i < smartlist_len(votes); ++i)
  1161. tor_free(flag_map[i]);
  1162. tor_free(flag_map);
  1163. tor_free(flag_counts);
  1164. tor_free(named_flag);
  1165. tor_free(unnamed_flag);
  1166. strmap_free(name_to_id_map, NULL);
  1167. smartlist_free(matching_descs);
  1168. smartlist_free(chosen_flags);
  1169. smartlist_free(versions);
  1170. smartlist_free(exitsummaries);
  1171. tor_free(bandwidths);
  1172. tor_free(measured_bws);
  1173. }
  1174. /* Add a signature. */
  1175. {
  1176. char digest[DIGEST256_LEN];
  1177. char fingerprint[HEX_DIGEST_LEN+1];
  1178. char signing_key_fingerprint[HEX_DIGEST_LEN+1];
  1179. digest_algorithm_t digest_alg =
  1180. flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
  1181. size_t digest_len =
  1182. flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
  1183. const char *algname = crypto_digest_algorithm_get_name(digest_alg);
  1184. char *buf = NULL;
  1185. char sigbuf[4096];
  1186. smartlist_add(chunks, tor_strdup("directory-signature "));
  1187. /* Compute the hash of the chunks. */
  1188. hash_list_members(digest, digest_len, chunks, digest_alg);
  1189. /* Get the fingerprints */
  1190. crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
  1191. crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
  1192. /* add the junk that will go at the end of the line. */
  1193. if (flavor == FLAV_NS) {
  1194. tor_asprintf(&buf, "%s %s\n", fingerprint,
  1195. signing_key_fingerprint);
  1196. } else {
  1197. tor_asprintf(&buf, "%s %s %s\n",
  1198. algname, fingerprint,
  1199. signing_key_fingerprint);
  1200. }
  1201. smartlist_add(chunks, buf);
  1202. /* And the signature. */
  1203. sigbuf[0] = '\0';
  1204. if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
  1205. digest, digest_len,
  1206. signing_key)) {
  1207. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1208. return NULL; /* This leaks, but it should never happen. */
  1209. }
  1210. smartlist_add(chunks, tor_strdup(sigbuf));
  1211. if (legacy_id_key_digest && legacy_signing_key && consensus_method >= 3) {
  1212. smartlist_add(chunks, tor_strdup("directory-signature "));
  1213. base16_encode(fingerprint, sizeof(fingerprint),
  1214. legacy_id_key_digest, DIGEST_LEN);
  1215. crypto_pk_get_fingerprint(legacy_signing_key,
  1216. signing_key_fingerprint, 0);
  1217. if (flavor == FLAV_NS) {
  1218. tor_asprintf(&buf, "%s %s\n", fingerprint,
  1219. signing_key_fingerprint);
  1220. } else {
  1221. tor_asprintf(&buf, "%s %s %s\n",
  1222. algname, fingerprint,
  1223. signing_key_fingerprint);
  1224. }
  1225. smartlist_add(chunks, buf);
  1226. sigbuf[0] = '\0';
  1227. if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
  1228. digest, digest_len,
  1229. legacy_signing_key)) {
  1230. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1231. return NULL; /* This leaks, but it should never happen. */
  1232. }
  1233. smartlist_add(chunks, tor_strdup(sigbuf));
  1234. }
  1235. }
  1236. result = smartlist_join_strings(chunks, "", 0, NULL);
  1237. tor_free(client_versions);
  1238. tor_free(server_versions);
  1239. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  1240. smartlist_free(flags);
  1241. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  1242. smartlist_free(chunks);
  1243. {
  1244. networkstatus_t *c;
  1245. if (!(c = networkstatus_parse_vote_from_string(result, NULL,
  1246. NS_TYPE_CONSENSUS))) {
  1247. log_err(LD_BUG,"Generated a networkstatus consensus we couldn't "
  1248. "parse.");
  1249. tor_free(result);
  1250. return NULL;
  1251. }
  1252. networkstatus_vote_free(c);
  1253. }
  1254. return result;
  1255. }
  1256. /** Given a consensus vote <b>target</b> and a set of detached signatures in
  1257. * <b>sigs</b> that correspond to the same consensus, check whether there are
  1258. * any new signatures in <b>src_voter_list</b> that should be added to
  1259. * <b>target</b>. (A signature should be added if we have no signature for that
  1260. * voter in <b>target</b> yet, or if we have no verifiable signature and the
  1261. * new signature is verifiable.) Return the number of signatures added or
  1262. * changed, or -1 if the document signed by <b>sigs</b> isn't the same
  1263. * document as <b>target</b>. */
  1264. int
  1265. networkstatus_add_detached_signatures(networkstatus_t *target,
  1266. ns_detached_signatures_t *sigs,
  1267. const char **msg_out)
  1268. {
  1269. int r = 0;
  1270. const char *flavor;
  1271. smartlist_t *siglist;
  1272. tor_assert(sigs);
  1273. tor_assert(target);
  1274. tor_assert(target->type == NS_TYPE_CONSENSUS);
  1275. flavor = networkstatus_get_flavor_name(target->flavor);
  1276. /* Do the times seem right? */
  1277. if (target->valid_after != sigs->valid_after) {
  1278. *msg_out = "Valid-After times do not match "
  1279. "when adding detached signatures to consensus";
  1280. return -1;
  1281. }
  1282. if (target->fresh_until != sigs->fresh_until) {
  1283. *msg_out = "Fresh-until times do not match "
  1284. "when adding detached signatures to consensus";
  1285. return -1;
  1286. }
  1287. if (target->valid_until != sigs->valid_until) {
  1288. *msg_out = "Valid-until times do not match "
  1289. "when adding detached signatures to consensus";
  1290. return -1;
  1291. }
  1292. siglist = strmap_get(sigs->signatures, flavor);
  1293. if (!siglist) {
  1294. *msg_out = "No signatures for given consensus flavor";
  1295. return -1;
  1296. }
  1297. /** Make sure all the digests we know match, and at least one matches. */
  1298. {
  1299. digests_t *digests = strmap_get(sigs->digests, flavor);
  1300. int n_matches = 0;
  1301. digest_algorithm_t alg;
  1302. if (!digests) {
  1303. *msg_out = "No digests for given consensus flavor";
  1304. return -1;
  1305. }
  1306. for (alg = DIGEST_SHA1; alg < N_DIGEST_ALGORITHMS; ++alg) {
  1307. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  1308. if (!memcmp(target->digests.d[alg], digests->d[alg], DIGEST256_LEN)) {
  1309. ++n_matches;
  1310. } else {
  1311. *msg_out = "Mismatched digest.";
  1312. return -1;
  1313. }
  1314. }
  1315. }
  1316. if (!n_matches) {
  1317. *msg_out = "No regognized digests for given consensus flavor";
  1318. }
  1319. }
  1320. /* For each voter in src... */
  1321. SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
  1322. char voter_identity[HEX_DIGEST_LEN+1];
  1323. networkstatus_voter_info_t *target_voter =
  1324. networkstatus_get_voter_by_id(target, sig->identity_digest);
  1325. authority_cert_t *cert = NULL;
  1326. const char *algorithm;
  1327. document_signature_t *old_sig = NULL;
  1328. algorithm = crypto_digest_algorithm_get_name(sig->alg);
  1329. base16_encode(voter_identity, sizeof(voter_identity),
  1330. sig->identity_digest, DIGEST_LEN);
  1331. log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
  1332. algorithm);
  1333. /* If the target doesn't know about this voter, then forget it. */
  1334. if (!target_voter) {
  1335. log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
  1336. continue;
  1337. }
  1338. old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
  1339. /* If the target already has a good signature from this voter, then skip
  1340. * this one. */
  1341. if (old_sig && old_sig->good_signature) {
  1342. log_info(LD_DIR, "We already have a good signature from %s using %s",
  1343. voter_identity, algorithm);
  1344. continue;
  1345. }
  1346. /* Try checking the signature if we haven't already. */
  1347. if (!sig->good_signature && !sig->bad_signature) {
  1348. cert = authority_cert_get_by_digests(sig->identity_digest,
  1349. sig->signing_key_digest);
  1350. if (cert)
  1351. networkstatus_check_document_signature(target, sig, cert);
  1352. }
  1353. /* If this signature is good, or we don't have any signature yet,
  1354. * then maybe add it. */
  1355. if (sig->good_signature || !old_sig || old_sig->bad_signature) {
  1356. log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
  1357. algorithm);
  1358. ++r;
  1359. if (old_sig) {
  1360. smartlist_remove(target_voter->sigs, old_sig);
  1361. document_signature_free(old_sig);
  1362. }
  1363. smartlist_add(target_voter->sigs, document_signature_dup(sig));
  1364. } else {
  1365. log_info(LD_DIR, "Not adding signature from %s", voter_identity);
  1366. }
  1367. } SMARTLIST_FOREACH_END(sig);
  1368. return r;
  1369. }
  1370. /** Return a newly allocated string containing all the signatures on
  1371. * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
  1372. * then the signatures will be put in a detached signatures document, so
  1373. * prefix any non-NS-flavored signatures with "additional-signature" rather
  1374. * than "directory-signature". */
  1375. static char *
  1376. networkstatus_format_signatures(networkstatus_t *consensus,
  1377. int for_detached_signatures)
  1378. {
  1379. smartlist_t *elements;
  1380. char buf[4096];
  1381. char *result = NULL;
  1382. int n_sigs = 0;
  1383. const consensus_flavor_t flavor = consensus->flavor;
  1384. const char *flavor_name = networkstatus_get_flavor_name(flavor);
  1385. const char *keyword;
  1386. if (for_detached_signatures && flavor != FLAV_NS)
  1387. keyword = "additional-signature";
  1388. else
  1389. keyword = "directory-signature";
  1390. elements = smartlist_create();
  1391. SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
  1392. SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
  1393. char sk[HEX_DIGEST_LEN+1];
  1394. char id[HEX_DIGEST_LEN+1];
  1395. if (!sig->signature || sig->bad_signature)
  1396. continue;
  1397. ++n_sigs;
  1398. base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
  1399. base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
  1400. if (flavor == FLAV_NS) {
  1401. tor_snprintf(buf, sizeof(buf),
  1402. "%s %s %s\n-----BEGIN SIGNATURE-----\n",
  1403. keyword, id, sk);
  1404. } else {
  1405. const char *digest_name =
  1406. crypto_digest_algorithm_get_name(sig->alg);
  1407. tor_snprintf(buf, sizeof(buf),
  1408. "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
  1409. keyword,
  1410. for_detached_signatures ? " " : "",
  1411. for_detached_signatures ? flavor_name : "",
  1412. digest_name, id, sk);
  1413. }
  1414. smartlist_add(elements, tor_strdup(buf));
  1415. base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len);
  1416. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  1417. smartlist_add(elements, tor_strdup(buf));
  1418. } SMARTLIST_FOREACH_END(sig);
  1419. } SMARTLIST_FOREACH_END(v);
  1420. result = smartlist_join_strings(elements, "", 0, NULL);
  1421. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1422. smartlist_free(elements);
  1423. if (!n_sigs)
  1424. tor_free(result);
  1425. return result;
  1426. }
  1427. /** Return a newly allocated string holding the detached-signatures document
  1428. * corresponding to the signatures on <b>consensuses</b>, which must contain
  1429. * exactly one FLAV_NS consensus, and no more than one consensus for each
  1430. * other flavor. */
  1431. char *
  1432. networkstatus_get_detached_signatures(smartlist_t *consensuses)
  1433. {
  1434. smartlist_t *elements;
  1435. char buf[4096];
  1436. char *result = NULL, *sigs = NULL;
  1437. networkstatus_t *consensus_ns = NULL;
  1438. tor_assert(consensuses);
  1439. SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
  1440. tor_assert(ns);
  1441. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  1442. if (ns && ns->flavor == FLAV_NS)
  1443. consensus_ns = ns;
  1444. });
  1445. if (!consensus_ns) {
  1446. log_warn(LD_BUG, "No NS consensus given.");
  1447. return NULL;
  1448. }
  1449. elements = smartlist_create();
  1450. {
  1451. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  1452. vu_buf[ISO_TIME_LEN+1];
  1453. char d[HEX_DIGEST_LEN+1];
  1454. base16_encode(d, sizeof(d),
  1455. consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
  1456. format_iso_time(va_buf, consensus_ns->valid_after);
  1457. format_iso_time(fu_buf, consensus_ns->fresh_until);
  1458. format_iso_time(vu_buf, consensus_ns->valid_until);
  1459. tor_snprintf(buf, sizeof(buf),
  1460. "consensus-digest %s\n"
  1461. "valid-after %s\n"
  1462. "fresh-until %s\n"
  1463. "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
  1464. smartlist_add(elements, tor_strdup(buf));
  1465. }
  1466. /* Get all the digests for the non-FLAV_NS consensuses */
  1467. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  1468. const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
  1469. int alg;
  1470. if (ns->flavor == FLAV_NS)
  1471. continue;
  1472. /* start with SHA256; we don't include SHA1 for anything but the basic
  1473. * consensus. */
  1474. for (alg = DIGEST_SHA256; alg < N_DIGEST_ALGORITHMS; ++alg) {
  1475. char d[HEX_DIGEST256_LEN+1];
  1476. const char *alg_name =
  1477. crypto_digest_algorithm_get_name(alg);
  1478. if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
  1479. continue;
  1480. base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
  1481. tor_snprintf(buf, sizeof(buf), "additional-digest %s %s %s\n",
  1482. flavor_name, alg_name, d);
  1483. smartlist_add(elements, tor_strdup(buf));
  1484. }
  1485. } SMARTLIST_FOREACH_END(ns);
  1486. /* Now get all the sigs for non-FLAV_NS consensuses */
  1487. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  1488. char *sigs;
  1489. if (ns->flavor == FLAV_NS)
  1490. continue;
  1491. sigs = networkstatus_format_signatures(ns, 1);
  1492. if (!sigs) {
  1493. log_warn(LD_DIR, "Couldn't format signatures");
  1494. goto err;
  1495. }
  1496. smartlist_add(elements, sigs);
  1497. } SMARTLIST_FOREACH_END(ns);
  1498. /* Now add the FLAV_NS consensus signatrures. */
  1499. sigs = networkstatus_format_signatures(consensus_ns, 1);
  1500. if (!sigs)
  1501. goto err;
  1502. smartlist_add(elements, sigs);
  1503. result = smartlist_join_strings(elements, "", 0, NULL);
  1504. err:
  1505. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1506. smartlist_free(elements);
  1507. return result;
  1508. }
  1509. /** Return a newly allocated string holding a detached-signatures document for
  1510. * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
  1511. * <b>pending</b>. */
  1512. static char *
  1513. get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
  1514. int n_flavors)
  1515. {
  1516. int flav;
  1517. char *signatures;
  1518. smartlist_t *c = smartlist_create();
  1519. for (flav = 0; flav < n_flavors; ++flav) {
  1520. if (pending[flav].consensus)
  1521. smartlist_add(c, pending[flav].consensus);
  1522. }
  1523. signatures = networkstatus_get_detached_signatures(c);
  1524. smartlist_free(c);
  1525. return signatures;
  1526. }
  1527. /** Release all storage held in <b>s</b>. */
  1528. void
  1529. ns_detached_signatures_free(ns_detached_signatures_t *s)
  1530. {
  1531. if (!s)
  1532. return;
  1533. if (s->signatures) {
  1534. STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
  1535. SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
  1536. document_signature_free(sig));
  1537. smartlist_free(sigs);
  1538. } STRMAP_FOREACH_END;
  1539. strmap_free(s->signatures, NULL);
  1540. strmap_free(s->digests, _tor_free);
  1541. }
  1542. tor_free(s);
  1543. }
  1544. /* =====
  1545. * Certificate functions
  1546. * ===== */
  1547. /** Allocate and return a new authority_cert_t with the same contents as
  1548. * <b>cert</b>. */
  1549. authority_cert_t *
  1550. authority_cert_dup(authority_cert_t *cert)
  1551. {
  1552. authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
  1553. tor_assert(cert);
  1554. memcpy(out, cert, sizeof(authority_cert_t));
  1555. /* Now copy pointed-to things. */
  1556. out->cache_info.signed_descriptor_body =
  1557. tor_strndup(cert->cache_info.signed_descriptor_body,
  1558. cert->cache_info.signed_descriptor_len);
  1559. out->cache_info.saved_location = SAVED_NOWHERE;
  1560. out->identity_key = crypto_pk_dup_key(cert->identity_key);
  1561. out->signing_key = crypto_pk_dup_key(cert->signing_key);
  1562. return out;
  1563. }
  1564. /* =====
  1565. * Vote scheduling
  1566. * ===== */
  1567. /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
  1568. * Note that these aren't the intervals we'll use to vote; they're the ones
  1569. * that we'll vote to use. */
  1570. void
  1571. dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
  1572. {
  1573. or_options_t *options = get_options();
  1574. tor_assert(timing_out);
  1575. timing_out->vote_interval = options->V3AuthVotingInterval;
  1576. timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
  1577. timing_out->vote_delay = options->V3AuthVoteDelay;
  1578. timing_out->dist_delay = options->V3AuthDistDelay;
  1579. }
  1580. /** Return the start of the next interval of size <b>interval</b> (in seconds)
  1581. * after <b>now</b>. Midnight always starts a fresh interval, and if the last
  1582. * interval of a day would be truncated to less than half its size, it is
  1583. * rolled into the previous interval. */
  1584. time_t
  1585. dirvote_get_start_of_next_interval(time_t now, int interval)
  1586. {
  1587. struct tm tm;
  1588. time_t midnight_today;
  1589. time_t midnight_tomorrow;
  1590. time_t next;
  1591. tor_gmtime_r(&now, &tm);
  1592. tm.tm_hour = 0;
  1593. tm.tm_min = 0;
  1594. tm.tm_sec = 0;
  1595. midnight_today = tor_timegm(&tm);
  1596. midnight_tomorrow = midnight_today + (24*60*60);
  1597. next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
  1598. /* Intervals never cross midnight. */
  1599. if (next > midnight_tomorrow)
  1600. next = midnight_tomorrow;
  1601. /* If the interval would only last half as long as it's supposed to, then
  1602. * skip over to the next day. */
  1603. if (next + interval/2 > midnight_tomorrow)
  1604. next = midnight_tomorrow;
  1605. return next;
  1606. }
  1607. /** Scheduling information for a voting interval. */
  1608. static struct {
  1609. /** When do we generate and distribute our vote for this interval? */
  1610. time_t voting_starts;
  1611. /** When do we send an HTTP request for any votes that we haven't
  1612. * been posted yet?*/
  1613. time_t fetch_missing_votes;
  1614. /** When do we give up on getting more votes and generate a consensus? */
  1615. time_t voting_ends;
  1616. /** When do we send an HTTP request for any signatures we're expecting to
  1617. * see on the consensus? */
  1618. time_t fetch_missing_signatures;
  1619. /** When do we publish the consensus? */
  1620. time_t interval_starts;
  1621. /* True iff we have generated and distributed our vote. */
  1622. int have_voted;
  1623. /* True iff we've requested missing votes. */
  1624. int have_fetched_missing_votes;
  1625. /* True iff we have built a consensus and sent the signatures around. */
  1626. int have_built_consensus;
  1627. /* True iff we've fetched missing signatures. */
  1628. int have_fetched_missing_signatures;
  1629. /* True iff we have published our consensus. */
  1630. int have_published_consensus;
  1631. } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
  1632. /** Set voting_schedule to hold the timing for the next vote we should be
  1633. * doing. */
  1634. void
  1635. dirvote_recalculate_timing(or_options_t *options, time_t now)
  1636. {
  1637. int interval, vote_delay, dist_delay;
  1638. time_t start;
  1639. time_t end;
  1640. networkstatus_t *consensus;
  1641. if (!authdir_mode_v3(options))
  1642. return;
  1643. consensus = networkstatus_get_live_consensus(now);
  1644. memset(&voting_schedule, 0, sizeof(voting_schedule));
  1645. if (consensus) {
  1646. interval = (int)( consensus->fresh_until - consensus->valid_after );
  1647. vote_delay = consensus->vote_seconds;
  1648. dist_delay = consensus->dist_seconds;
  1649. } else {
  1650. interval = options->TestingV3AuthInitialVotingInterval;
  1651. vote_delay = options->TestingV3AuthInitialVoteDelay;
  1652. dist_delay = options->TestingV3AuthInitialDistDelay;
  1653. }
  1654. tor_assert(interval > 0);
  1655. if (vote_delay + dist_delay > interval/2)
  1656. vote_delay = dist_delay = interval / 4;
  1657. start = voting_schedule.interval_starts =
  1658. dirvote_get_start_of_next_interval(now,interval);
  1659. end = dirvote_get_start_of_next_interval(start+1, interval);
  1660. tor_assert(end > start);
  1661. voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
  1662. voting_schedule.voting_ends = start - dist_delay;
  1663. voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
  1664. voting_schedule.voting_starts = start - dist_delay - vote_delay;
  1665. {
  1666. char tbuf[ISO_TIME_LEN+1];
  1667. format_iso_time(tbuf, voting_schedule.interval_starts);
  1668. log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
  1669. "consensus_set=%d, interval=%d",
  1670. tbuf, consensus?1:0, interval);
  1671. }
  1672. }
  1673. /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
  1674. void
  1675. dirvote_act(or_options_t *options, time_t now)
  1676. {
  1677. if (!authdir_mode_v3(options))
  1678. return;
  1679. if (!voting_schedule.voting_starts) {
  1680. char *keys = list_v3_auth_ids();
  1681. authority_cert_t *c = get_my_v3_authority_cert();
  1682. log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
  1683. "Mine is %s.",
  1684. keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
  1685. tor_free(keys);
  1686. dirvote_recalculate_timing(options, now);
  1687. }
  1688. if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
  1689. log_notice(LD_DIR, "Time to vote.");
  1690. dirvote_perform_vote();
  1691. voting_schedule.have_voted = 1;
  1692. }
  1693. if (voting_schedule.fetch_missing_votes < now &&
  1694. !voting_schedule.have_fetched_missing_votes) {
  1695. log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
  1696. dirvote_fetch_missing_votes();
  1697. voting_schedule.have_fetched_missing_votes = 1;
  1698. }
  1699. if (voting_schedule.voting_ends < now &&
  1700. !voting_schedule.have_built_consensus) {
  1701. log_notice(LD_DIR, "Time to compute a consensus.");
  1702. dirvote_compute_consensuses();
  1703. /* XXXX We will want to try again later if we haven't got enough
  1704. * votes yet. Implement this if it turns out to ever happen. */
  1705. voting_schedule.have_built_consensus = 1;
  1706. }
  1707. if (voting_schedule.fetch_missing_signatures < now &&
  1708. !voting_schedule.have_fetched_missing_signatures) {
  1709. log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
  1710. dirvote_fetch_missing_signatures();
  1711. voting_schedule.have_fetched_missing_signatures = 1;
  1712. }
  1713. if (voting_schedule.interval_starts < now &&
  1714. !voting_schedule.have_published_consensus) {
  1715. log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
  1716. dirvote_publish_consensus();
  1717. dirvote_clear_votes(0);
  1718. voting_schedule.have_published_consensus = 1;
  1719. /* XXXX We will want to try again later if we haven't got enough
  1720. * signatures yet. Implement this if it turns out to ever happen. */
  1721. dirvote_recalculate_timing(options, now);
  1722. }
  1723. }
  1724. /** A vote networkstatus_t and its unparsed body: held around so we can
  1725. * use it to generate a consensus (at voting_ends) and so we can serve it to
  1726. * other authorities that might want it. */
  1727. typedef struct pending_vote_t {
  1728. cached_dir_t *vote_body;
  1729. networkstatus_t *vote;
  1730. } pending_vote_t;
  1731. /** List of pending_vote_t for the current vote. Before we've used them to
  1732. * build a consensus, the votes go here. */
  1733. static smartlist_t *pending_vote_list = NULL;
  1734. /** List of pending_vote_t for the previous vote. After we've used them to
  1735. * build a consensus, the votes go here for the next period. */
  1736. static smartlist_t *previous_vote_list = NULL;
  1737. static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
  1738. /** The detached signatures for the consensus that we're currently
  1739. * building. */
  1740. static char *pending_consensus_signatures = NULL;
  1741. /** List of ns_detached_signatures_t: hold signatures that get posted to us
  1742. * before we have generated the consensus on our own. */
  1743. static smartlist_t *pending_consensus_signature_list = NULL;
  1744. /** Generate a networkstatus vote and post it to all the v3 authorities.
  1745. * (V3 Authority only) */
  1746. static int
  1747. dirvote_perform_vote(void)
  1748. {
  1749. crypto_pk_env_t *key = get_my_v3_authority_signing_key();
  1750. authority_cert_t *cert = get_my_v3_authority_cert();
  1751. networkstatus_t *ns;
  1752. char *contents;
  1753. pending_vote_t *pending_vote;
  1754. time_t now = time(NULL);
  1755. int status;
  1756. const char *msg = "";
  1757. if (!cert || !key) {
  1758. log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
  1759. return -1;
  1760. } else if (cert->expires < now) {
  1761. log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
  1762. return -1;
  1763. }
  1764. if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
  1765. return -1;
  1766. contents = format_networkstatus_vote(key, ns);
  1767. networkstatus_vote_free(ns);
  1768. if (!contents)
  1769. return -1;
  1770. pending_vote = dirvote_add_vote(contents, &msg, &status);
  1771. tor_free(contents);
  1772. if (!pending_vote) {
  1773. log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
  1774. msg);
  1775. return -1;
  1776. }
  1777. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
  1778. ROUTER_PURPOSE_GENERAL,
  1779. V3_AUTHORITY,
  1780. pending_vote->vote_body->dir,
  1781. pending_vote->vote_body->dir_len, 0);
  1782. log_notice(LD_DIR, "Vote posted.");
  1783. return 0;
  1784. }
  1785. /** Send an HTTP request to every other v3 authority, for the votes of every
  1786. * authority for which we haven't received a vote yet in this period. (V3
  1787. * authority only) */
  1788. static void
  1789. dirvote_fetch_missing_votes(void)
  1790. {
  1791. smartlist_t *missing_fps = smartlist_create();
  1792. char *resource;
  1793. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1794. trusted_dir_server_t *, ds,
  1795. {
  1796. if (!(ds->type & V3_AUTHORITY))
  1797. continue;
  1798. if (!dirvote_get_vote(ds->v3_identity_digest,
  1799. DGV_BY_ID|DGV_INCLUDE_PENDING)) {
  1800. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  1801. base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
  1802. DIGEST_LEN);
  1803. smartlist_add(missing_fps, cp);
  1804. }
  1805. });
  1806. if (!smartlist_len(missing_fps)) {
  1807. smartlist_free(missing_fps);
  1808. return;
  1809. }
  1810. log_notice(LOG_NOTICE, "We're missing votes from %d authorities. Asking "
  1811. "every other authority for a copy.", smartlist_len(missing_fps));
  1812. resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
  1813. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
  1814. 0, resource);
  1815. tor_free(resource);
  1816. SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
  1817. smartlist_free(missing_fps);
  1818. }
  1819. /** Send a request to every other authority for its detached signatures,
  1820. * unless we have signatures from all other v3 authorities already. */
  1821. static void
  1822. dirvote_fetch_missing_signatures(void)
  1823. {
  1824. int need_any = 0;
  1825. int i;
  1826. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  1827. networkstatus_t *consensus = pending_consensuses[i].consensus;
  1828. if (!consensus ||
  1829. networkstatus_check_consensus_signature(consensus, -1) == 1) {
  1830. /* We have no consensus, or we have one that's signed by everybody. */
  1831. continue;
  1832. }
  1833. need_any = 1;
  1834. }
  1835. if (!need_any)
  1836. return;
  1837. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
  1838. 0, NULL);
  1839. }
  1840. /** Release all storage held by pending consensuses (those waiting for
  1841. * signatures). */
  1842. static void
  1843. dirvote_clear_pending_consensuses(void)
  1844. {
  1845. int i;
  1846. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1847. pending_consensus_t *pc = &pending_consensuses[i];
  1848. tor_free(pc->body);
  1849. networkstatus_vote_free(pc->consensus);
  1850. pc->consensus = NULL;
  1851. }
  1852. }
  1853. /** Drop all currently pending votes, consensus, and detached signatures. */
  1854. static void
  1855. dirvote_clear_votes(int all_votes)
  1856. {
  1857. if (!previous_vote_list)
  1858. previous_vote_list = smartlist_create();
  1859. if (!pending_vote_list)
  1860. pending_vote_list = smartlist_create();
  1861. /* All "previous" votes are now junk. */
  1862. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
  1863. cached_dir_decref(v->vote_body);
  1864. v->vote_body = NULL;
  1865. networkstatus_vote_free(v->vote);
  1866. tor_free(v);
  1867. });
  1868. smartlist_clear(previous_vote_list);
  1869. if (all_votes) {
  1870. /* If we're dumping all the votes, we delete the pending ones. */
  1871. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1872. cached_dir_decref(v->vote_body);
  1873. v->vote_body = NULL;
  1874. networkstatus_vote_free(v->vote);
  1875. tor_free(v);
  1876. });
  1877. } else {
  1878. /* Otherwise, we move them into "previous". */
  1879. smartlist_add_all(previous_vote_list, pending_vote_list);
  1880. }
  1881. smartlist_clear(pending_vote_list);
  1882. if (pending_consensus_signature_list) {
  1883. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
  1884. tor_free(cp));
  1885. smartlist_clear(pending_consensus_signature_list);
  1886. }
  1887. tor_free(pending_consensus_signatures);
  1888. dirvote_clear_pending_consensuses();
  1889. }
  1890. /** Return a newly allocated string containing the hex-encoded v3 authority
  1891. identity digest of every recognized v3 authority. */
  1892. static char *
  1893. list_v3_auth_ids(void)
  1894. {
  1895. smartlist_t *known_v3_keys = smartlist_create();
  1896. char *keys;
  1897. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1898. trusted_dir_server_t *, ds,
  1899. if ((ds->type & V3_AUTHORITY) &&
  1900. !tor_digest_is_zero(ds->v3_identity_digest))
  1901. smartlist_add(known_v3_keys,
  1902. tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
  1903. keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
  1904. SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
  1905. smartlist_free(known_v3_keys);
  1906. return keys;
  1907. }
  1908. /** Called when we have received a networkstatus vote in <b>vote_body</b>.
  1909. * Parse and validate it, and on success store it as a pending vote (which we
  1910. * then return). Return NULL on failure. Sets *<b>msg_out</b> and
  1911. * *<b>status_out</b> to an HTTP response and status code. (V3 authority
  1912. * only) */
  1913. pending_vote_t *
  1914. dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
  1915. {
  1916. networkstatus_t *vote;
  1917. networkstatus_voter_info_t *vi;
  1918. trusted_dir_server_t *ds;
  1919. pending_vote_t *pending_vote = NULL;
  1920. const char *end_of_vote = NULL;
  1921. int any_failed = 0;
  1922. tor_assert(vote_body);
  1923. tor_assert(msg_out);
  1924. tor_assert(status_out);
  1925. if (!pending_vote_list)
  1926. pending_vote_list = smartlist_create();
  1927. *status_out = 0;
  1928. *msg_out = NULL;
  1929. again:
  1930. vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
  1931. NS_TYPE_VOTE);
  1932. if (!end_of_vote)
  1933. end_of_vote = vote_body + strlen(vote_body);
  1934. if (!vote) {
  1935. log_warn(LD_DIR, "Couldn't parse vote: length was %d",
  1936. (int)strlen(vote_body));
  1937. *msg_out = "Unable to parse vote";
  1938. goto err;
  1939. }
  1940. tor_assert(smartlist_len(vote->voters) == 1);
  1941. vi = get_voter(vote);
  1942. {
  1943. int any_sig_good = 0;
  1944. SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
  1945. if (sig->good_signature)
  1946. any_sig_good = 1);
  1947. tor_assert(any_sig_good);
  1948. }
  1949. ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
  1950. if (!ds) {
  1951. char *keys = list_v3_auth_ids();
  1952. log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
  1953. "with authority key ID %s. "
  1954. "This key ID is not recognized. Known v3 key IDs are: %s",
  1955. vi->nickname, vi->address,
  1956. hex_str(vi->identity_digest, DIGEST_LEN), keys);
  1957. tor_free(keys);
  1958. *msg_out = "Vote not from a recognized v3 authority";
  1959. goto err;
  1960. }
  1961. tor_assert(vote->cert);
  1962. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1963. vote->cert->signing_key_digest)) {
  1964. /* Hey, it's a new cert! */
  1965. trusted_dirs_load_certs_from_string(
  1966. vote->cert->cache_info.signed_descriptor_body,
  1967. 0 /* from_store */, 1 /*flush*/);
  1968. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1969. vote->cert->signing_key_digest)) {
  1970. log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
  1971. }
  1972. }
  1973. /* Is it for the right period? */
  1974. if (vote->valid_after != voting_schedule.interval_starts) {
  1975. char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
  1976. format_iso_time(tbuf1, vote->valid_after);
  1977. format_iso_time(tbuf2, voting_schedule.interval_starts);
  1978. log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
  1979. "we were expecting %s", vi->address, tbuf1, tbuf2);
  1980. *msg_out = "Bad valid-after time";
  1981. goto err;
  1982. }
  1983. /* Now see whether we already have a vote from this authority. */
  1984. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1985. if (! memcmp(v->vote->cert->cache_info.identity_digest,
  1986. vote->cert->cache_info.identity_digest,
  1987. DIGEST_LEN)) {
  1988. networkstatus_voter_info_t *vi_old = get_voter(v->vote);
  1989. if (!memcmp(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
  1990. /* Ah, it's the same vote. Not a problem. */
  1991. log_info(LD_DIR, "Discarding a vote we already have.");
  1992. if (*status_out < 200)
  1993. *status_out = 200;
  1994. goto discard;
  1995. } else if (v->vote->published < vote->published) {
  1996. log_notice(LD_DIR, "Replacing an older pending vote from this "
  1997. "directory.");
  1998. cached_dir_decref(v->vote_body);
  1999. networkstatus_vote_free(v->vote);
  2000. v->vote_body = new_cached_dir(tor_strndup(vote_body,
  2001. end_of_vote-vote_body),
  2002. vote->published);
  2003. v->vote = vote;
  2004. if (end_of_vote &&
  2005. !strcmpstart(end_of_vote, "network-status-version"))
  2006. goto again;
  2007. if (*status_out < 200)
  2008. *status_out = 200;
  2009. if (!*msg_out)
  2010. *msg_out = "OK";
  2011. return v;
  2012. } else {
  2013. *msg_out = "Already have a newer pending vote";
  2014. goto err;
  2015. }
  2016. }
  2017. });
  2018. pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
  2019. pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
  2020. end_of_vote-vote_body),
  2021. vote->published);
  2022. pending_vote->vote = vote;
  2023. smartlist_add(pending_vote_list, pending_vote);
  2024. if (!strcmpstart(end_of_vote, "network-status-version ")) {
  2025. vote_body = end_of_vote;
  2026. goto again;
  2027. }
  2028. goto done;
  2029. err:
  2030. any_failed = 1;
  2031. if (!*msg_out)
  2032. *msg_out = "Error adding vote";
  2033. if (*status_out < 400)
  2034. *status_out = 400;
  2035. discard:
  2036. networkstatus_vote_free(vote);
  2037. if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
  2038. vote_body = end_of_vote;
  2039. goto again;
  2040. }
  2041. done:
  2042. if (*status_out < 200)
  2043. *status_out = 200;
  2044. if (!*msg_out) {
  2045. if (!any_failed && !pending_vote) {
  2046. *msg_out = "Duplicate discarded";
  2047. } else {
  2048. *msg_out = "ok";
  2049. }
  2050. }
  2051. return any_failed ? NULL : pending_vote;
  2052. }
  2053. /** Try to compute a v3 networkstatus consensus from the currently pending
  2054. * votes. Return 0 on success, -1 on failure. Store the consensus in
  2055. * pending_consensus: it won't be ready to be published until we have
  2056. * everybody else's signatures collected too. (V3 Authority only) */
  2057. static int
  2058. dirvote_compute_consensuses(void)
  2059. {
  2060. /* Have we got enough votes to try? */
  2061. int n_votes, n_voters, n_vote_running = 0;
  2062. smartlist_t *votes = NULL, *votestrings = NULL;
  2063. char *consensus_body = NULL, *signatures = NULL, *votefile;
  2064. networkstatus_t *consensus = NULL;
  2065. authority_cert_t *my_cert;
  2066. pending_consensus_t pending[N_CONSENSUS_FLAVORS];
  2067. int flav;
  2068. memset(pending, 0, sizeof(pending));
  2069. if (!pending_vote_list)
  2070. pending_vote_list = smartlist_create();
  2071. n_voters = get_n_authorities(V3_AUTHORITY);
  2072. n_votes = smartlist_len(pending_vote_list);
  2073. if (n_votes <= n_voters/2) {
  2074. log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
  2075. "%d of %d", n_votes, n_voters/2);
  2076. goto err;
  2077. }
  2078. tor_assert(pending_vote_list);
  2079. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  2080. if (smartlist_string_isin(v->vote->known_flags, "Running"))
  2081. n_vote_running++;
  2082. });
  2083. if (!n_vote_running) {
  2084. /* See task 1066. */
  2085. log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
  2086. "and publishing a consensus without Running nodes "
  2087. "would make many clients stop working. Not "
  2088. "generating a consensus!");
  2089. goto err;
  2090. }
  2091. if (!(my_cert = get_my_v3_authority_cert())) {
  2092. log_warn(LD_DIR, "Can't generate consensus without a certificate.");
  2093. goto err;
  2094. }
  2095. votes = smartlist_create();
  2096. votestrings = smartlist_create();
  2097. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
  2098. {
  2099. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  2100. c->bytes = v->vote_body->dir;
  2101. c->len = v->vote_body->dir_len;
  2102. smartlist_add(votestrings, c); /* collect strings to write to disk */
  2103. smartlist_add(votes, v->vote); /* collect votes to compute consensus */
  2104. });
  2105. votefile = get_datadir_fname("v3-status-votes");
  2106. write_chunks_to_file(votefile, votestrings, 0);
  2107. tor_free(votefile);
  2108. SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
  2109. smartlist_free(votestrings);
  2110. {
  2111. char legacy_dbuf[DIGEST_LEN];
  2112. crypto_pk_env_t *legacy_sign=NULL;
  2113. char *legacy_id_digest = NULL;
  2114. int n_generated = 0;
  2115. if (get_options()->V3AuthUseLegacyKey) {
  2116. authority_cert_t *cert = get_my_v3_legacy_cert();
  2117. legacy_sign = get_my_v3_legacy_signing_key();
  2118. if (cert) {
  2119. crypto_pk_get_digest(cert->identity_key, legacy_dbuf);
  2120. legacy_id_digest = legacy_dbuf;
  2121. }
  2122. }
  2123. for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  2124. const char *flavor_name = networkstatus_get_flavor_name(flav);
  2125. consensus_body = networkstatus_compute_consensus(
  2126. votes, n_voters,
  2127. my_cert->identity_key,
  2128. get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
  2129. flav);
  2130. if (!consensus_body) {
  2131. log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
  2132. flavor_name);
  2133. continue;
  2134. }
  2135. consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
  2136. NS_TYPE_CONSENSUS);
  2137. if (!consensus) {
  2138. log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
  2139. flavor_name);
  2140. tor_free(consensus_body);
  2141. continue;
  2142. }
  2143. /* 'Check' our own signature, to mark it valid. */
  2144. networkstatus_check_consensus_signature(consensus, -1);
  2145. pending[flav].body = consensus_body;
  2146. pending[flav].consensus = consensus;
  2147. n_generated++;
  2148. consensus_body = NULL;
  2149. consensus = NULL;
  2150. }
  2151. if (!n_generated) {
  2152. log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
  2153. goto err;
  2154. }
  2155. }
  2156. signatures = get_detached_signatures_from_pending_consensuses(
  2157. pending, N_CONSENSUS_FLAVORS);
  2158. if (!signatures) {
  2159. log_warn(LD_DIR, "Couldn't extract signatures.");
  2160. goto err;
  2161. }
  2162. dirvote_clear_pending_consensuses();
  2163. memcpy(pending_consensuses, pending, sizeof(pending));
  2164. tor_free(pending_consensus_signatures);
  2165. pending_consensus_signatures = signatures;
  2166. if (pending_consensus_signature_list) {
  2167. int n_sigs = 0;
  2168. /* we may have gotten signatures for this consensus before we built
  2169. * it ourself. Add them now. */
  2170. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, sig,
  2171. {
  2172. const char *msg = NULL;
  2173. int r = dirvote_add_signatures_to_all_pending_consensuses(sig, &msg);
  2174. if (r >= 0)
  2175. n_sigs += r;
  2176. else
  2177. log_warn(LD_DIR,
  2178. "Could not add queued signature to new consensus: %s",
  2179. msg);
  2180. tor_free(sig);
  2181. });
  2182. if (n_sigs)
  2183. log_notice(LD_DIR, "Added %d pending signatures while building "
  2184. "consensus.", n_sigs);
  2185. smartlist_clear(pending_consensus_signature_list);
  2186. }
  2187. log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
  2188. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
  2189. ROUTER_PURPOSE_GENERAL,
  2190. V3_AUTHORITY,
  2191. pending_consensus_signatures,
  2192. strlen(pending_consensus_signatures), 0);
  2193. log_notice(LD_DIR, "Signature(s) posted.");
  2194. return 0;
  2195. err:
  2196. smartlist_free(votes);
  2197. tor_free(consensus_body);
  2198. tor_free(signatures);
  2199. networkstatus_vote_free(consensus);
  2200. return -1;
  2201. }
  2202. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  2203. * signatures on the currently pending consensus. Add them to <b>pc</b>
  2204. * as appropriate. Return the number of signatures added. (?) */
  2205. static int
  2206. dirvote_add_signatures_to_pending_consensus(
  2207. pending_consensus_t *pc,
  2208. ns_detached_signatures_t *sigs,
  2209. const char **msg_out)
  2210. {
  2211. const char *flavor_name;
  2212. int r = -1;
  2213. /* Only call if we have a pending consensus right now. */
  2214. tor_assert(pc->consensus);
  2215. tor_assert(pc->body);
  2216. tor_assert(pending_consensus_signatures);
  2217. flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
  2218. *msg_out = NULL;
  2219. {
  2220. smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
  2221. log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
  2222. sig_list ? smartlist_len(sig_list) : 0, flavor_name);
  2223. }
  2224. r = networkstatus_add_detached_signatures(pc->consensus, sigs, msg_out);
  2225. log_info(LD_DIR,"Added %d signatures to consensus.", r);
  2226. if (r >= 1) {
  2227. char *new_signatures =
  2228. networkstatus_format_signatures(pc->consensus, 0);
  2229. char *dst, *dst_end;
  2230. size_t new_consensus_len;
  2231. if (!new_signatures) {
  2232. *msg_out = "No signatures to add";
  2233. goto err;
  2234. }
  2235. new_consensus_len =
  2236. strlen(pc->body) + strlen(new_signatures) + 1;
  2237. pc->body = tor_realloc(pc->body, new_consensus_len);
  2238. dst_end = pc->body + new_consensus_len;
  2239. dst = strstr(pc->body, "directory-signature ");
  2240. tor_assert(dst);
  2241. strlcpy(dst, new_signatures, dst_end-dst);
  2242. /* We remove this block once it has failed to crash for a while. But
  2243. * unless it shows up in profiles, we're probably better leaving it in,
  2244. * just in case we break detached signature processing at some point. */
  2245. {
  2246. networkstatus_t *v = networkstatus_parse_vote_from_string(
  2247. pc->body, NULL,
  2248. NS_TYPE_CONSENSUS);
  2249. tor_assert(v);
  2250. networkstatus_vote_free(v);
  2251. }
  2252. *msg_out = "Signatures added";
  2253. } else if (r == 0) {
  2254. *msg_out = "Signatures ignored";
  2255. } else {
  2256. goto err;
  2257. }
  2258. goto done;
  2259. err:
  2260. if (!*msg_out)
  2261. *msg_out = "Unrecognized error while adding detached signatures.";
  2262. done:
  2263. return r;
  2264. }
  2265. static int
  2266. dirvote_add_signatures_to_all_pending_consensuses(
  2267. const char *detached_signatures_body,
  2268. const char **msg_out)
  2269. {
  2270. int r=0, i, n_added = 0, errors = 0;
  2271. ns_detached_signatures_t *sigs;
  2272. tor_assert(detached_signatures_body);
  2273. tor_assert(msg_out);
  2274. tor_assert(pending_consensus_signatures);
  2275. if (!(sigs = networkstatus_parse_detached_signatures(
  2276. detached_signatures_body, NULL))) {
  2277. *msg_out = "Couldn't parse detached signatures.";
  2278. goto err;
  2279. }
  2280. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  2281. int res;
  2282. pending_consensus_t *pc = &pending_consensuses[i];
  2283. if (!pc->consensus)
  2284. continue;
  2285. res = dirvote_add_signatures_to_pending_consensus(pc, sigs, msg_out);
  2286. if (res < 0)
  2287. errors++;
  2288. else
  2289. n_added += res;
  2290. }
  2291. if (errors && !n_added) {
  2292. r = -1;
  2293. goto err;
  2294. }
  2295. if (n_added && pending_consensuses[FLAV_NS].consensus) {
  2296. char *new_detached =
  2297. get_detached_signatures_from_pending_consensuses(
  2298. pending_consensuses, N_CONSENSUS_FLAVORS);
  2299. if (new_detached) {
  2300. tor_free(pending_consensus_signatures);
  2301. pending_consensus_signatures = new_detached;
  2302. }
  2303. }
  2304. r = n_added;
  2305. goto done;
  2306. err:
  2307. if (!*msg_out)
  2308. *msg_out = "Unrecognized error while adding detached signatures.";
  2309. done:
  2310. ns_detached_signatures_free(sigs);
  2311. /* XXXX NM Check how return is used. We can now have an error *and*
  2312. signatures added. */
  2313. return r;
  2314. }
  2315. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  2316. * signatures on the currently pending consensus. Add them to the pending
  2317. * consensus (if we have one); otherwise queue them until we have a
  2318. * consensus. Return negative on failure, nonnegative on success. */
  2319. int
  2320. dirvote_add_signatures(const char *detached_signatures_body,
  2321. const char *source,
  2322. const char **msg)
  2323. {
  2324. if (pending_consensuses[FLAV_NS].consensus) {
  2325. log_notice(LD_DIR, "Got a signature from %s. "
  2326. "Adding it to the pending consensus.", source);
  2327. return dirvote_add_signatures_to_all_pending_consensuses(
  2328. detached_signatures_body, msg);
  2329. } else {
  2330. log_notice(LD_DIR, "Got a signature from %s. "
  2331. "Queuing it for the next consensus.", source);
  2332. if (!pending_consensus_signature_list)
  2333. pending_consensus_signature_list = smartlist_create();
  2334. smartlist_add(pending_consensus_signature_list,
  2335. tor_strdup(detached_signatures_body));
  2336. *msg = "Signature queued";
  2337. return 0;
  2338. }
  2339. }
  2340. /** Replace the consensus that we're currently serving with the one that we've
  2341. * been building. (V3 Authority only) */
  2342. static int
  2343. dirvote_publish_consensus(void)
  2344. {
  2345. int i;
  2346. /* Now remember all the other consensuses as if we were a directory cache. */
  2347. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  2348. pending_consensus_t *pending = &pending_consensuses[i];
  2349. const char *name;
  2350. name = networkstatus_get_flavor_name(i);
  2351. tor_assert(name);
  2352. if (!pending->consensus ||
  2353. networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
  2354. log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
  2355. continue;
  2356. }
  2357. if (networkstatus_set_current_consensus(pending->body, name, 0))
  2358. log_warn(LD_DIR, "Error publishing %s consensus", name);
  2359. else
  2360. log_notice(LD_DIR, "Published %s consensus", name);
  2361. }
  2362. return 0;
  2363. }
  2364. /** Release all static storage held in dirvote.c */
  2365. void
  2366. dirvote_free_all(void)
  2367. {
  2368. dirvote_clear_votes(1);
  2369. /* now empty as a result of clear_pending_votes. */
  2370. smartlist_free(pending_vote_list);
  2371. pending_vote_list = NULL;
  2372. smartlist_free(previous_vote_list);
  2373. previous_vote_list = NULL;
  2374. dirvote_clear_pending_consensuses();
  2375. tor_free(pending_consensus_signatures);
  2376. if (pending_consensus_signature_list) {
  2377. /* now empty as a result of clear_pending_votes. */
  2378. smartlist_free(pending_consensus_signature_list);
  2379. pending_consensus_signature_list = NULL;
  2380. }
  2381. }
  2382. /* ====
  2383. * Access to pending items.
  2384. * ==== */
  2385. /** Return the body of the consensus that we're currently trying to build. */
  2386. const char *
  2387. dirvote_get_pending_consensus(consensus_flavor_t flav)
  2388. {
  2389. tor_assert(((int)flav) >= 0 && flav < N_CONSENSUS_FLAVORS);
  2390. return pending_consensuses[flav].body;
  2391. }
  2392. /** Return the signatures that we know for the consensus that we're currently
  2393. * trying to build. */
  2394. const char *
  2395. dirvote_get_pending_detached_signatures(void)
  2396. {
  2397. return pending_consensus_signatures;
  2398. }
  2399. /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
  2400. * vote for the authority with the v3 authority identity key digest <b>fp</b>;
  2401. * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
  2402. * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
  2403. * false, do not consider any votes for a consensus that's already been built.
  2404. * If <b>include_pending</b> is false, do not consider any votes for the
  2405. * consensus that's in progress. May return NULL if we have no vote for the
  2406. * authority in question. */
  2407. const cached_dir_t *
  2408. dirvote_get_vote(const char *fp, int flags)
  2409. {
  2410. int by_id = flags & DGV_BY_ID;
  2411. const int include_pending = flags & DGV_INCLUDE_PENDING;
  2412. const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
  2413. if (!pending_vote_list && !previous_vote_list)
  2414. return NULL;
  2415. if (fp == NULL) {
  2416. authority_cert_t *c = get_my_v3_authority_cert();
  2417. if (c) {
  2418. fp = c->cache_info.identity_digest;
  2419. by_id = 1;
  2420. } else
  2421. return NULL;
  2422. }
  2423. if (by_id) {
  2424. if (pending_vote_list && include_pending) {
  2425. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  2426. if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  2427. return pv->vote_body);
  2428. }
  2429. if (previous_vote_list && include_previous) {
  2430. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  2431. if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  2432. return pv->vote_body);
  2433. }
  2434. } else {
  2435. if (pending_vote_list && include_pending) {
  2436. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  2437. if (!memcmp(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  2438. return pv->vote_body);
  2439. }
  2440. if (previous_vote_list && include_previous) {
  2441. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  2442. if (!memcmp(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  2443. return pv->vote_body);
  2444. }
  2445. }
  2446. return NULL;
  2447. }
  2448. /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>.
  2449. *
  2450. * XXX Right now, there is only one way to generate microdescriptors from
  2451. * router descriptors. This may change in future consensus methods. If so,
  2452. * we'll need an internal way to remember which method we used, and ask for a
  2453. * particular method.
  2454. **/
  2455. microdesc_t *
  2456. dirvote_create_microdescriptor(const routerinfo_t *ri)
  2457. {
  2458. microdesc_t *result = NULL;
  2459. char *key = NULL, *summary = NULL, *family = NULL;
  2460. char buf[1024];
  2461. size_t keylen;
  2462. char *out = buf, *end = buf+sizeof(buf);
  2463. if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
  2464. goto done;
  2465. summary = policy_summarize(ri->exit_policy);
  2466. if (ri->declared_family)
  2467. family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
  2468. if (tor_snprintf(out, end-out, "onion-key\n%s", key)<0)
  2469. goto done;
  2470. out += strlen(out);
  2471. if (family) {
  2472. if (tor_snprintf(out, end-out, "family %s\n", family)<0)
  2473. goto done;
  2474. out += strlen(out);
  2475. }
  2476. if (summary && strcmp(summary, "reject 1-65535")) {
  2477. if (tor_snprintf(out, end-out, "p %s\n", summary)<0)
  2478. goto done;
  2479. out += strlen(out);
  2480. }
  2481. *out = '\0'; /* Make sure it's nul-terminated. This should be a no-op */
  2482. {
  2483. smartlist_t *lst = microdescs_parse_from_string(buf, out, 0, 1);
  2484. if (smartlist_len(lst) != 1) {
  2485. log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
  2486. SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
  2487. smartlist_free(lst);
  2488. goto done;
  2489. }
  2490. result = smartlist_get(lst, 0);
  2491. smartlist_free(lst);
  2492. }
  2493. done:
  2494. tor_free(key);
  2495. tor_free(summary);
  2496. tor_free(family);
  2497. return result;
  2498. }
  2499. /** Cached space-separated string to hold */
  2500. static char *microdesc_consensus_methods = NULL;
  2501. /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
  2502. * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
  2503. * in <b>out</b>. Return -1 on failure and the number of characters written
  2504. * on success. */
  2505. ssize_t
  2506. dirvote_format_microdesc_vote_line(char *out, size_t out_len,
  2507. const microdesc_t *md)
  2508. {
  2509. char d64[BASE64_DIGEST256_LEN+1];
  2510. if (!microdesc_consensus_methods) {
  2511. microdesc_consensus_methods =
  2512. make_consensus_method_list(MIN_METHOD_FOR_MICRODESC,
  2513. MAX_SUPPORTED_CONSENSUS_METHOD,
  2514. ",");
  2515. tor_assert(microdesc_consensus_methods);
  2516. }
  2517. if (digest256_to_base64(d64, md->digest)<0)
  2518. return -1;
  2519. if (tor_snprintf(out, out_len, "m %s sha256=%s\n",
  2520. microdesc_consensus_methods, d64)<0)
  2521. return -1;
  2522. return strlen(out);
  2523. }
  2524. /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
  2525. * the digest algorithm <b>alg</b>, decode it and copy it into
  2526. * <b>digest256_out</b> and return 0. Otherwise return -1. */
  2527. int
  2528. vote_routerstatus_find_microdesc_hash(char *digest256_out,
  2529. const vote_routerstatus_t *vrs,
  2530. int method,
  2531. digest_algorithm_t alg)
  2532. {
  2533. /* XXXX only returns the sha256 method. */
  2534. const vote_microdesc_hash_t *h;
  2535. char mstr[64];
  2536. size_t mlen;
  2537. char dstr[64];
  2538. tor_snprintf(mstr, sizeof(mstr), "%d", method);
  2539. mlen = strlen(mstr);
  2540. tor_snprintf(dstr, sizeof(dstr), " %s=",
  2541. crypto_digest_algorithm_get_name(alg));
  2542. for (h = vrs->microdesc; h; h = h->next) {
  2543. const char *cp = h->microdesc_hash_line;
  2544. size_t num_len;
  2545. /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
  2546. * the first part. */
  2547. while (1) {
  2548. num_len = strspn(cp, "1234567890");
  2549. if (num_len == mlen && !memcmp(mstr, cp, mlen)) {
  2550. /* This is the line. */
  2551. char buf[BASE64_DIGEST256_LEN+1];
  2552. /* XXXX ignores extraneous stuff if the digest is too long. This
  2553. * seems harmless enough, right? */
  2554. cp = strstr(cp, dstr);
  2555. if (!cp)
  2556. return -1;
  2557. cp += strlen(dstr);
  2558. strlcpy(buf, cp, sizeof(buf));
  2559. return digest256_from_base64(digest256_out, buf);
  2560. }
  2561. if (num_len == 0 || cp[num_len] != ',')
  2562. break;
  2563. cp += num_len + 1;
  2564. }
  2565. }
  2566. return -1;
  2567. }