dirvote.c 124 KB

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