dirvote.c 132 KB

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