dirvote.c 132 KB

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