dirvote.c 160 KB

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