dirvote.c 124 KB

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