dirvote.c 124 KB

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