dirvote.c 127 KB

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