dirvote.c 162 KB

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