dirvote.c 127 KB

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