dirvote.c 158 KB

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