dirvote.c 124 KB

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