dirvote.c 136 KB

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