dirvote.c 142 KB

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