dirvote.c 159 KB

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