dirvote.c 127 KB

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