dirvote.c 132 KB

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