dirvote.c 137 KB

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