dirvote.c 140 KB

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