dirvote.c 134 KB

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