dirvote.c 136 KB

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