dirvote.c 164 KB

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