dirvote.c 133 KB

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