dirvote.c 114 KB

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