dirvote.c 164 KB

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