dirvote.c 125 KB

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