dirvote.c 162 KB

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