dirvote.c 125 KB

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