dirvote.c 141 KB

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