dirvote.c 162 KB

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