dirvote.c 162 KB

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