dirvote.c 129 KB

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