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