dirvote.c 125 KB

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