dirvote.c 140 KB

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