dirvote.c 124 KB

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