dirvote.c 159 KB

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