dirvote.c 159 KB

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