dirvote.c 140 KB

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