dirvote.c 139 KB

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