dirvote.c 165 KB

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