dirvote.c 131 KB

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