dirvote.c 140 KB

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