dirvote.c 159 KB

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