dirvote.c 140 KB

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