dirvote.c 130 KB

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