dirvote.c 138 KB

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