dirvote.c 127 KB

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