dirvote.c 126 KB

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