dirvote.c 162 KB

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