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