dirvote.c 124 KB

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