dirvote.c 139 KB

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