dirvote.c 141 KB

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