dirvote.c 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961
  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 = compute_protover_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 *exitsummaries = smartlist_new();
  1406. uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
  1407. sizeof(uint32_t));
  1408. uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
  1409. sizeof(uint32_t));
  1410. uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
  1411. sizeof(uint32_t));
  1412. int num_bandwidths;
  1413. int num_mbws;
  1414. int num_guardfraction_inputs;
  1415. int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
  1416. * votes[j] knows about. */
  1417. int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
  1418. * about flags[f]. */
  1419. int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
  1420. * is the same flag as votes[j]->known_flags[b]. */
  1421. int *named_flag; /* Index of the flag "Named" for votes[j] */
  1422. int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
  1423. int n_authorities_measuring_bandwidth;
  1424. strmap_t *name_to_id_map = strmap_new();
  1425. char conflict[DIGEST_LEN];
  1426. char unknown[DIGEST_LEN];
  1427. memset(conflict, 0, sizeof(conflict));
  1428. memset(unknown, 0xff, sizeof(conflict));
  1429. size = tor_calloc(smartlist_len(votes), sizeof(int));
  1430. n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
  1431. n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
  1432. flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
  1433. named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
  1434. unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
  1435. for (i = 0; i < smartlist_len(votes); ++i)
  1436. unnamed_flag[i] = named_flag[i] = -1;
  1437. /* Build the flag indexes. Note that no vote can have more than 64 members
  1438. * for known_flags, so no value will be greater than 63, so it's safe to
  1439. * do U64_LITERAL(1) << index on these values. But note also that
  1440. * named_flag and unnamed_flag are initialized to -1, so we need to check
  1441. * that they're actually set before doing U64_LITERAL(1) << index with
  1442. * them.*/
  1443. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1444. flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
  1445. sizeof(int));
  1446. if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  1447. log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
  1448. smartlist_len(v->known_flags));
  1449. }
  1450. SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
  1451. int p = smartlist_string_pos(flags, fl);
  1452. tor_assert(p >= 0);
  1453. flag_map[v_sl_idx][fl_sl_idx] = p;
  1454. ++n_flag_voters[p];
  1455. if (!strcmp(fl, "Named"))
  1456. named_flag[v_sl_idx] = fl_sl_idx;
  1457. if (!strcmp(fl, "Unnamed"))
  1458. unnamed_flag[v_sl_idx] = fl_sl_idx;
  1459. } SMARTLIST_FOREACH_END(fl);
  1460. n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
  1461. size[v_sl_idx] = smartlist_len(v->routerstatus_list);
  1462. } SMARTLIST_FOREACH_END(v);
  1463. /* Named and Unnamed get treated specially */
  1464. {
  1465. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1466. uint64_t nf;
  1467. if (named_flag[v_sl_idx]<0)
  1468. continue;
  1469. nf = U64_LITERAL(1) << named_flag[v_sl_idx];
  1470. SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
  1471. vote_routerstatus_t *, rs) {
  1472. if ((rs->flags & nf) != 0) {
  1473. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  1474. if (!d) {
  1475. /* We have no name officially mapped to this digest. */
  1476. strmap_set_lc(name_to_id_map, rs->status.nickname,
  1477. rs->status.identity_digest);
  1478. } else if (d != conflict &&
  1479. fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  1480. /* Authorities disagree about this nickname. */
  1481. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  1482. } else {
  1483. /* It's already a conflict, or it's already this ID. */
  1484. }
  1485. }
  1486. } SMARTLIST_FOREACH_END(rs);
  1487. } SMARTLIST_FOREACH_END(v);
  1488. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1489. uint64_t uf;
  1490. if (unnamed_flag[v_sl_idx]<0)
  1491. continue;
  1492. uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
  1493. SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
  1494. vote_routerstatus_t *, rs) {
  1495. if ((rs->flags & uf) != 0) {
  1496. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  1497. if (d == conflict || d == unknown) {
  1498. /* Leave it alone; we know what it is. */
  1499. } else if (!d) {
  1500. /* We have no name officially mapped to this digest. */
  1501. strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
  1502. } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
  1503. /* Authorities disagree about this nickname. */
  1504. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  1505. } else {
  1506. /* It's mapped to a different name. */
  1507. }
  1508. }
  1509. } SMARTLIST_FOREACH_END(rs);
  1510. } SMARTLIST_FOREACH_END(v);
  1511. }
  1512. /* We need to know how many votes measure bandwidth. */
  1513. n_authorities_measuring_bandwidth = 0;
  1514. SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
  1515. if (v->has_measured_bws) {
  1516. ++n_authorities_measuring_bandwidth;
  1517. }
  1518. );
  1519. /* Populate the collator */
  1520. collator = dircollator_new(smartlist_len(votes), total_authorities);
  1521. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1522. dircollator_add_vote(collator, v);
  1523. } SMARTLIST_FOREACH_END(v);
  1524. dircollator_collate(collator, consensus_method);
  1525. /* Now go through all the votes */
  1526. flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
  1527. const int num_routers = dircollator_n_routers(collator);
  1528. for (i = 0; i < num_routers; ++i) {
  1529. vote_routerstatus_t **vrs_lst =
  1530. dircollator_get_votes_for_router(collator, i);
  1531. vote_routerstatus_t *rs;
  1532. routerstatus_t rs_out;
  1533. const char *current_rsa_id = NULL;
  1534. const char *chosen_version;
  1535. const char *chosen_name = NULL;
  1536. int exitsummary_disagreement = 0;
  1537. int is_named = 0, is_unnamed = 0, is_running = 0;
  1538. int is_guard = 0, is_exit = 0, is_bad_exit = 0;
  1539. int naming_conflict = 0;
  1540. int n_listing = 0;
  1541. char microdesc_digest[DIGEST256_LEN];
  1542. tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
  1543. memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
  1544. smartlist_clear(matching_descs);
  1545. smartlist_clear(chosen_flags);
  1546. smartlist_clear(versions);
  1547. num_bandwidths = 0;
  1548. num_mbws = 0;
  1549. num_guardfraction_inputs = 0;
  1550. int ed_consensus = 0;
  1551. const uint8_t *ed_consensus_val = NULL;
  1552. /* Okay, go through all the entries for this digest. */
  1553. for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
  1554. if (vrs_lst[voter_idx] == NULL)
  1555. continue; /* This voter had nothing to say about this entry. */
  1556. rs = vrs_lst[voter_idx];
  1557. ++n_listing;
  1558. current_rsa_id = rs->status.identity_digest;
  1559. smartlist_add(matching_descs, rs);
  1560. if (rs->version && rs->version[0])
  1561. smartlist_add(versions, rs->version);
  1562. /* Tally up all the flags. */
  1563. for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
  1564. if (rs->flags & (U64_LITERAL(1) << flag))
  1565. ++flag_counts[flag_map[voter_idx][flag]];
  1566. }
  1567. if (named_flag[voter_idx] >= 0 &&
  1568. (rs->flags & (U64_LITERAL(1) << named_flag[voter_idx]))) {
  1569. if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
  1570. log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
  1571. chosen_name, rs->status.nickname);
  1572. naming_conflict = 1;
  1573. }
  1574. chosen_name = rs->status.nickname;
  1575. }
  1576. /* Count guardfraction votes and note down the values. */
  1577. if (rs->status.has_guardfraction) {
  1578. measured_guardfraction[num_guardfraction_inputs++] =
  1579. rs->status.guardfraction_percentage;
  1580. }
  1581. /* count bandwidths */
  1582. if (rs->has_measured_bw)
  1583. measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
  1584. if (rs->status.has_bandwidth)
  1585. bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
  1586. /* Count number for which ed25519 is canonical. */
  1587. if (rs->ed25519_reflects_consensus) {
  1588. ++ed_consensus;
  1589. if (ed_consensus_val) {
  1590. tor_assert(fast_memeq(ed_consensus_val, rs->ed25519_id,
  1591. ED25519_PUBKEY_LEN));
  1592. } else {
  1593. ed_consensus_val = rs->ed25519_id;
  1594. }
  1595. }
  1596. }
  1597. /* We don't include this router at all unless more than half of
  1598. * the authorities we believe in list it. */
  1599. if (n_listing <= total_authorities/2)
  1600. continue;
  1601. if (ed_consensus > 0) {
  1602. tor_assert(consensus_method >= MIN_METHOD_FOR_ED25519_ID_VOTING);
  1603. if (ed_consensus <= total_authorities / 2) {
  1604. log_warn(LD_BUG, "Not enough entries had ed_consensus set; how "
  1605. "can we have a consensus of %d?", ed_consensus);
  1606. }
  1607. }
  1608. /* The clangalyzer can't figure out that this will never be NULL
  1609. * if n_listing is at least 1 */
  1610. tor_assert(current_rsa_id);
  1611. /* Figure out the most popular opinion of what the most recent
  1612. * routerinfo and its contents are. */
  1613. memset(microdesc_digest, 0, sizeof(microdesc_digest));
  1614. rs = compute_routerstatus_consensus(matching_descs, consensus_method,
  1615. microdesc_digest, &alt_orport);
  1616. /* Copy bits of that into rs_out. */
  1617. memset(&rs_out, 0, sizeof(rs_out));
  1618. tor_assert(fast_memeq(current_rsa_id,
  1619. rs->status.identity_digest,DIGEST_LEN));
  1620. memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
  1621. memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
  1622. DIGEST_LEN);
  1623. rs_out.addr = rs->status.addr;
  1624. rs_out.published_on = rs->status.published_on;
  1625. rs_out.dir_port = rs->status.dir_port;
  1626. rs_out.or_port = rs->status.or_port;
  1627. if (consensus_method >= MIN_METHOD_FOR_A_LINES) {
  1628. tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
  1629. rs_out.ipv6_orport = alt_orport.port;
  1630. }
  1631. rs_out.has_bandwidth = 0;
  1632. rs_out.has_exitsummary = 0;
  1633. if (chosen_name && !naming_conflict) {
  1634. strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
  1635. } else {
  1636. strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
  1637. }
  1638. {
  1639. const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
  1640. if (!d) {
  1641. is_named = is_unnamed = 0;
  1642. } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
  1643. is_named = 1; is_unnamed = 0;
  1644. } else {
  1645. is_named = 0; is_unnamed = 1;
  1646. }
  1647. }
  1648. /* Set the flags. */
  1649. smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
  1650. SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
  1651. if (!strcmp(fl, "Named")) {
  1652. if (is_named)
  1653. smartlist_add(chosen_flags, (char*)fl);
  1654. } else if (!strcmp(fl, "Unnamed")) {
  1655. if (is_unnamed)
  1656. smartlist_add(chosen_flags, (char*)fl);
  1657. } else if (!strcmp(fl, "NoEdConsensus") &&
  1658. consensus_method >= MIN_METHOD_FOR_ED25519_ID_VOTING) {
  1659. if (ed_consensus <= total_authorities/2)
  1660. smartlist_add(chosen_flags, (char*)fl);
  1661. } else {
  1662. if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
  1663. smartlist_add(chosen_flags, (char*)fl);
  1664. if (!strcmp(fl, "Exit"))
  1665. is_exit = 1;
  1666. else if (!strcmp(fl, "Guard"))
  1667. is_guard = 1;
  1668. else if (!strcmp(fl, "Running"))
  1669. is_running = 1;
  1670. else if (!strcmp(fl, "BadExit"))
  1671. is_bad_exit = 1;
  1672. }
  1673. }
  1674. } SMARTLIST_FOREACH_END(fl);
  1675. /* Starting with consensus method 4 we do not list servers
  1676. * that are not running in a consensus. See Proposal 138 */
  1677. if (!is_running)
  1678. continue;
  1679. /* Pick the version. */
  1680. if (smartlist_len(versions)) {
  1681. sort_version_list(versions, 0);
  1682. chosen_version = get_most_frequent_member(versions);
  1683. } else {
  1684. chosen_version = NULL;
  1685. }
  1686. /* If it's a guard and we have enough guardfraction votes,
  1687. calculate its consensus guardfraction value. */
  1688. if (is_guard && num_guardfraction_inputs > 2 &&
  1689. consensus_method >= MIN_METHOD_FOR_GUARDFRACTION) {
  1690. rs_out.has_guardfraction = 1;
  1691. rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
  1692. num_guardfraction_inputs);
  1693. /* final value should be an integer percentage! */
  1694. tor_assert(rs_out.guardfraction_percentage <= 100);
  1695. }
  1696. /* Pick a bandwidth */
  1697. if (num_mbws > 2) {
  1698. rs_out.has_bandwidth = 1;
  1699. rs_out.bw_is_unmeasured = 0;
  1700. rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
  1701. } else if (num_bandwidths > 0) {
  1702. rs_out.has_bandwidth = 1;
  1703. rs_out.bw_is_unmeasured = 1;
  1704. rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
  1705. if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW &&
  1706. n_authorities_measuring_bandwidth > 2) {
  1707. /* Cap non-measured bandwidths. */
  1708. if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
  1709. rs_out.bandwidth_kb = max_unmeasured_bw_kb;
  1710. }
  1711. }
  1712. }
  1713. /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
  1714. is_exit = is_exit && !is_bad_exit;
  1715. /* Update total bandwidth weights with the bandwidths of this router. */
  1716. {
  1717. update_total_bandwidth_weights(&rs_out,
  1718. is_exit, is_guard,
  1719. &G, &M, &E, &D, &T);
  1720. }
  1721. /* Ok, we already picked a descriptor digest we want to list
  1722. * previously. Now we want to use the exit policy summary from
  1723. * that descriptor. If everybody plays nice all the voters who
  1724. * listed that descriptor will have the same summary. If not then
  1725. * something is fishy and we'll use the most common one (breaking
  1726. * ties in favor of lexicographically larger one (only because it
  1727. * lets me reuse more existing code)).
  1728. *
  1729. * The other case that can happen is that no authority that voted
  1730. * for that descriptor has an exit policy summary. That's
  1731. * probably quite unlikely but can happen. In that case we use
  1732. * the policy that was most often listed in votes, again breaking
  1733. * ties like in the previous case.
  1734. */
  1735. {
  1736. /* Okay, go through all the votes for this router. We prepared
  1737. * that list previously */
  1738. const char *chosen_exitsummary = NULL;
  1739. smartlist_clear(exitsummaries);
  1740. SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
  1741. /* Check if the vote where this status comes from had the
  1742. * proper descriptor */
  1743. tor_assert(fast_memeq(rs_out.identity_digest,
  1744. vsr->status.identity_digest,
  1745. DIGEST_LEN));
  1746. if (vsr->status.has_exitsummary &&
  1747. fast_memeq(rs_out.descriptor_digest,
  1748. vsr->status.descriptor_digest,
  1749. DIGEST_LEN)) {
  1750. tor_assert(vsr->status.exitsummary);
  1751. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1752. if (!chosen_exitsummary) {
  1753. chosen_exitsummary = vsr->status.exitsummary;
  1754. } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
  1755. /* Great. There's disagreement among the voters. That
  1756. * really shouldn't be */
  1757. exitsummary_disagreement = 1;
  1758. }
  1759. }
  1760. } SMARTLIST_FOREACH_END(vsr);
  1761. if (exitsummary_disagreement) {
  1762. char id[HEX_DIGEST_LEN+1];
  1763. char dd[HEX_DIGEST_LEN+1];
  1764. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1765. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1766. log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
  1767. " for router %s with descriptor %s. This really shouldn't"
  1768. " have happened.", id, dd);
  1769. smartlist_sort_strings(exitsummaries);
  1770. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1771. } else if (!chosen_exitsummary) {
  1772. char id[HEX_DIGEST_LEN+1];
  1773. char dd[HEX_DIGEST_LEN+1];
  1774. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1775. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1776. log_warn(LD_DIR, "Not one of the voters that made us select"
  1777. "descriptor %s for router %s had an exit policy"
  1778. "summary", dd, id);
  1779. /* Ok, none of those voting for the digest we chose had an
  1780. * exit policy for us. Well, that kinda sucks.
  1781. */
  1782. smartlist_clear(exitsummaries);
  1783. SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
  1784. if (vsr->status.has_exitsummary)
  1785. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1786. });
  1787. smartlist_sort_strings(exitsummaries);
  1788. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1789. if (!chosen_exitsummary)
  1790. log_warn(LD_DIR, "Wow, not one of the voters had an exit "
  1791. "policy summary for %s. Wow.", id);
  1792. }
  1793. if (chosen_exitsummary) {
  1794. rs_out.has_exitsummary = 1;
  1795. /* yea, discards the const */
  1796. rs_out.exitsummary = (char *)chosen_exitsummary;
  1797. }
  1798. }
  1799. if (flavor == FLAV_MICRODESC &&
  1800. tor_digest256_is_zero(microdesc_digest)) {
  1801. /* With no microdescriptor digest, we omit the entry entirely. */
  1802. continue;
  1803. }
  1804. {
  1805. char *buf;
  1806. /* Okay!! Now we can write the descriptor... */
  1807. /* First line goes into "buf". */
  1808. buf = routerstatus_format_entry(&rs_out, NULL, NULL, rs_format, NULL);
  1809. if (buf)
  1810. smartlist_add(chunks, buf);
  1811. }
  1812. /* Now an m line, if applicable. */
  1813. if (flavor == FLAV_MICRODESC &&
  1814. !tor_digest256_is_zero(microdesc_digest)) {
  1815. char m[BASE64_DIGEST256_LEN+1];
  1816. digest256_to_base64(m, microdesc_digest);
  1817. smartlist_add_asprintf(chunks, "m %s\n", m);
  1818. }
  1819. /* Next line is all flags. The "\n" is missing. */
  1820. smartlist_add(chunks,
  1821. smartlist_join_strings(chosen_flags, " ", 0, NULL));
  1822. /* Now the version line. */
  1823. if (chosen_version) {
  1824. smartlist_add(chunks, tor_strdup("\nv "));
  1825. smartlist_add(chunks, tor_strdup(chosen_version));
  1826. }
  1827. smartlist_add(chunks, tor_strdup("\n"));
  1828. /* Now the weight line. */
  1829. if (rs_out.has_bandwidth) {
  1830. char *guardfraction_str = NULL;
  1831. int unmeasured = rs_out.bw_is_unmeasured &&
  1832. consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW;
  1833. /* If we have guardfraction info, include it in the 'w' line. */
  1834. if (rs_out.has_guardfraction) {
  1835. tor_asprintf(&guardfraction_str,
  1836. " GuardFraction=%u", rs_out.guardfraction_percentage);
  1837. }
  1838. smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
  1839. rs_out.bandwidth_kb,
  1840. unmeasured?" Unmeasured=1":"",
  1841. guardfraction_str ? guardfraction_str : "");
  1842. tor_free(guardfraction_str);
  1843. }
  1844. /* Now the exitpolicy summary line. */
  1845. if (rs_out.has_exitsummary && flavor == FLAV_NS) {
  1846. smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
  1847. }
  1848. /* And the loop is over and we move on to the next router */
  1849. }
  1850. tor_free(size);
  1851. tor_free(n_voter_flags);
  1852. tor_free(n_flag_voters);
  1853. for (i = 0; i < smartlist_len(votes); ++i)
  1854. tor_free(flag_map[i]);
  1855. tor_free(flag_map);
  1856. tor_free(flag_counts);
  1857. tor_free(named_flag);
  1858. tor_free(unnamed_flag);
  1859. strmap_free(name_to_id_map, NULL);
  1860. smartlist_free(matching_descs);
  1861. smartlist_free(chosen_flags);
  1862. smartlist_free(versions);
  1863. smartlist_free(exitsummaries);
  1864. tor_free(bandwidths_kb);
  1865. tor_free(measured_bws_kb);
  1866. tor_free(measured_guardfraction);
  1867. }
  1868. /* Mark the directory footer region */
  1869. smartlist_add(chunks, tor_strdup("directory-footer\n"));
  1870. {
  1871. int64_t weight_scale = BW_WEIGHT_SCALE;
  1872. char *bw_weight_param = NULL;
  1873. // Parse params, extract BW_WEIGHT_SCALE if present
  1874. // DO NOT use consensus_param_bw_weight_scale() in this code!
  1875. // The consensus is not formed yet!
  1876. /* XXXX Extract this code into a common function. Or not: #19011. */
  1877. if (params) {
  1878. if (strcmpstart(params, "bwweightscale=") == 0)
  1879. bw_weight_param = params;
  1880. else
  1881. bw_weight_param = strstr(params, " bwweightscale=");
  1882. }
  1883. if (bw_weight_param) {
  1884. int ok=0;
  1885. char *eq = strchr(bw_weight_param, '=');
  1886. if (eq) {
  1887. weight_scale = tor_parse_long(eq+1, 10, 1, INT32_MAX, &ok,
  1888. NULL);
  1889. if (!ok) {
  1890. log_warn(LD_DIR, "Bad element '%s' in bw weight param",
  1891. escaped(bw_weight_param));
  1892. weight_scale = BW_WEIGHT_SCALE;
  1893. }
  1894. } else {
  1895. log_warn(LD_DIR, "Bad element '%s' in bw weight param",
  1896. escaped(bw_weight_param));
  1897. weight_scale = BW_WEIGHT_SCALE;
  1898. }
  1899. }
  1900. added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
  1901. T, weight_scale);
  1902. }
  1903. /* Add a signature. */
  1904. {
  1905. char digest[DIGEST256_LEN];
  1906. char fingerprint[HEX_DIGEST_LEN+1];
  1907. char signing_key_fingerprint[HEX_DIGEST_LEN+1];
  1908. digest_algorithm_t digest_alg =
  1909. flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
  1910. size_t digest_len =
  1911. flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
  1912. const char *algname = crypto_digest_algorithm_get_name(digest_alg);
  1913. char *signature;
  1914. smartlist_add(chunks, tor_strdup("directory-signature "));
  1915. /* Compute the hash of the chunks. */
  1916. crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
  1917. /* Get the fingerprints */
  1918. crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
  1919. crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
  1920. /* add the junk that will go at the end of the line. */
  1921. if (flavor == FLAV_NS) {
  1922. smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
  1923. signing_key_fingerprint);
  1924. } else {
  1925. smartlist_add_asprintf(chunks, "%s %s %s\n",
  1926. algname, fingerprint,
  1927. signing_key_fingerprint);
  1928. }
  1929. /* And the signature. */
  1930. if (!(signature = router_get_dirobj_signature(digest, digest_len,
  1931. signing_key))) {
  1932. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1933. goto done;
  1934. }
  1935. smartlist_add(chunks, signature);
  1936. if (legacy_id_key_digest && legacy_signing_key) {
  1937. smartlist_add(chunks, tor_strdup("directory-signature "));
  1938. base16_encode(fingerprint, sizeof(fingerprint),
  1939. legacy_id_key_digest, DIGEST_LEN);
  1940. crypto_pk_get_fingerprint(legacy_signing_key,
  1941. signing_key_fingerprint, 0);
  1942. if (flavor == FLAV_NS) {
  1943. smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
  1944. signing_key_fingerprint);
  1945. } else {
  1946. smartlist_add_asprintf(chunks, "%s %s %s\n",
  1947. algname, fingerprint,
  1948. signing_key_fingerprint);
  1949. }
  1950. if (!(signature = router_get_dirobj_signature(digest, digest_len,
  1951. legacy_signing_key))) {
  1952. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1953. goto done;
  1954. }
  1955. smartlist_add(chunks, signature);
  1956. }
  1957. }
  1958. result = smartlist_join_strings(chunks, "", 0, NULL);
  1959. {
  1960. networkstatus_t *c;
  1961. if (!(c = networkstatus_parse_vote_from_string(result, NULL,
  1962. NS_TYPE_CONSENSUS))) {
  1963. log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
  1964. "parse.");
  1965. tor_free(result);
  1966. goto done;
  1967. }
  1968. // Verify balancing parameters
  1969. if (added_weights) {
  1970. networkstatus_verify_bw_weights(c, consensus_method);
  1971. }
  1972. networkstatus_vote_free(c);
  1973. }
  1974. done:
  1975. dircollator_free(collator);
  1976. tor_free(client_versions);
  1977. tor_free(server_versions);
  1978. tor_free(packages);
  1979. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  1980. smartlist_free(flags);
  1981. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  1982. smartlist_free(chunks);
  1983. SMARTLIST_FOREACH(param_list, char *, cp, tor_free(cp));
  1984. smartlist_free(param_list);
  1985. return result;
  1986. }
  1987. /** Given a list of networkstatus_t for each vote, return a newly allocated
  1988. * string containing the "package" lines for the vote. */
  1989. STATIC char *
  1990. compute_consensus_package_lines(smartlist_t *votes)
  1991. {
  1992. const int n_votes = smartlist_len(votes);
  1993. /* This will be a map from "packagename version" strings to arrays
  1994. * of const char *, with the i'th member of the array corresponding to the
  1995. * package line from the i'th vote.
  1996. */
  1997. strmap_t *package_status = strmap_new();
  1998. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1999. if (! v->package_lines)
  2000. continue;
  2001. SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
  2002. if (! validate_recommended_package_line(line))
  2003. continue;
  2004. /* Skip 'cp' to the second space in the line. */
  2005. const char *cp = strchr(line, ' ');
  2006. if (!cp) continue;
  2007. ++cp;
  2008. cp = strchr(cp, ' ');
  2009. if (!cp) continue;
  2010. char *key = tor_strndup(line, cp - line);
  2011. const char **status = strmap_get(package_status, key);
  2012. if (!status) {
  2013. status = tor_calloc(n_votes, sizeof(const char *));
  2014. strmap_set(package_status, key, status);
  2015. }
  2016. status[v_sl_idx] = line; /* overwrite old value */
  2017. tor_free(key);
  2018. } SMARTLIST_FOREACH_END(line);
  2019. } SMARTLIST_FOREACH_END(v);
  2020. smartlist_t *entries = smartlist_new(); /* temporary */
  2021. smartlist_t *result_list = smartlist_new(); /* output */
  2022. STRMAP_FOREACH(package_status, key, const char **, values) {
  2023. int i, count=-1;
  2024. for (i = 0; i < n_votes; ++i) {
  2025. if (values[i])
  2026. smartlist_add(entries, (void*) values[i]);
  2027. }
  2028. smartlist_sort_strings(entries);
  2029. int n_voting_for_entry = smartlist_len(entries);
  2030. const char *most_frequent =
  2031. smartlist_get_most_frequent_string_(entries, &count);
  2032. if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
  2033. smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
  2034. }
  2035. smartlist_clear(entries);
  2036. } STRMAP_FOREACH_END;
  2037. smartlist_sort_strings(result_list);
  2038. char *result = smartlist_join_strings(result_list, "", 0, NULL);
  2039. SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
  2040. smartlist_free(result_list);
  2041. smartlist_free(entries);
  2042. strmap_free(package_status, tor_free_);
  2043. return result;
  2044. }
  2045. /** Given a consensus vote <b>target</b> and a set of detached signatures in
  2046. * <b>sigs</b> that correspond to the same consensus, check whether there are
  2047. * any new signatures in <b>src_voter_list</b> that should be added to
  2048. * <b>target</b>. (A signature should be added if we have no signature for that
  2049. * voter in <b>target</b> yet, or if we have no verifiable signature and the
  2050. * new signature is verifiable.) Return the number of signatures added or
  2051. * changed, or -1 if the document signed by <b>sigs</b> isn't the same
  2052. * document as <b>target</b>. */
  2053. int
  2054. networkstatus_add_detached_signatures(networkstatus_t *target,
  2055. ns_detached_signatures_t *sigs,
  2056. const char *source,
  2057. int severity,
  2058. const char **msg_out)
  2059. {
  2060. int r = 0;
  2061. const char *flavor;
  2062. smartlist_t *siglist;
  2063. tor_assert(sigs);
  2064. tor_assert(target);
  2065. tor_assert(target->type == NS_TYPE_CONSENSUS);
  2066. flavor = networkstatus_get_flavor_name(target->flavor);
  2067. /* Do the times seem right? */
  2068. if (target->valid_after != sigs->valid_after) {
  2069. *msg_out = "Valid-After times do not match "
  2070. "when adding detached signatures to consensus";
  2071. return -1;
  2072. }
  2073. if (target->fresh_until != sigs->fresh_until) {
  2074. *msg_out = "Fresh-until times do not match "
  2075. "when adding detached signatures to consensus";
  2076. return -1;
  2077. }
  2078. if (target->valid_until != sigs->valid_until) {
  2079. *msg_out = "Valid-until times do not match "
  2080. "when adding detached signatures to consensus";
  2081. return -1;
  2082. }
  2083. siglist = strmap_get(sigs->signatures, flavor);
  2084. if (!siglist) {
  2085. *msg_out = "No signatures for given consensus flavor";
  2086. return -1;
  2087. }
  2088. /** Make sure all the digests we know match, and at least one matches. */
  2089. {
  2090. common_digests_t *digests = strmap_get(sigs->digests, flavor);
  2091. int n_matches = 0;
  2092. int alg;
  2093. if (!digests) {
  2094. *msg_out = "No digests for given consensus flavor";
  2095. return -1;
  2096. }
  2097. for (alg = DIGEST_SHA1; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
  2098. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  2099. if (fast_memeq(target->digests.d[alg], digests->d[alg],
  2100. DIGEST256_LEN)) {
  2101. ++n_matches;
  2102. } else {
  2103. *msg_out = "Mismatched digest.";
  2104. return -1;
  2105. }
  2106. }
  2107. }
  2108. if (!n_matches) {
  2109. *msg_out = "No recognized digests for given consensus flavor";
  2110. }
  2111. }
  2112. /* For each voter in src... */
  2113. SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
  2114. char voter_identity[HEX_DIGEST_LEN+1];
  2115. networkstatus_voter_info_t *target_voter =
  2116. networkstatus_get_voter_by_id(target, sig->identity_digest);
  2117. authority_cert_t *cert = NULL;
  2118. const char *algorithm;
  2119. document_signature_t *old_sig = NULL;
  2120. algorithm = crypto_digest_algorithm_get_name(sig->alg);
  2121. base16_encode(voter_identity, sizeof(voter_identity),
  2122. sig->identity_digest, DIGEST_LEN);
  2123. log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
  2124. algorithm);
  2125. /* If the target doesn't know about this voter, then forget it. */
  2126. if (!target_voter) {
  2127. log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
  2128. continue;
  2129. }
  2130. old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
  2131. /* If the target already has a good signature from this voter, then skip
  2132. * this one. */
  2133. if (old_sig && old_sig->good_signature) {
  2134. log_info(LD_DIR, "We already have a good signature from %s using %s",
  2135. voter_identity, algorithm);
  2136. continue;
  2137. }
  2138. /* Try checking the signature if we haven't already. */
  2139. if (!sig->good_signature && !sig->bad_signature) {
  2140. cert = authority_cert_get_by_digests(sig->identity_digest,
  2141. sig->signing_key_digest);
  2142. if (cert) {
  2143. /* Not checking the return value here, since we are going to look
  2144. * at the status of sig->good_signature in a moment. */
  2145. (void) networkstatus_check_document_signature(target, sig, cert);
  2146. }
  2147. }
  2148. /* If this signature is good, or we don't have any signature yet,
  2149. * then maybe add it. */
  2150. if (sig->good_signature || !old_sig || old_sig->bad_signature) {
  2151. log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
  2152. algorithm);
  2153. tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
  2154. target_voter->nickname, source);
  2155. ++r;
  2156. if (old_sig) {
  2157. smartlist_remove(target_voter->sigs, old_sig);
  2158. document_signature_free(old_sig);
  2159. }
  2160. smartlist_add(target_voter->sigs, document_signature_dup(sig));
  2161. } else {
  2162. log_info(LD_DIR, "Not adding signature from %s", voter_identity);
  2163. }
  2164. } SMARTLIST_FOREACH_END(sig);
  2165. return r;
  2166. }
  2167. /** Return a newly allocated string containing all the signatures on
  2168. * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
  2169. * then the signatures will be put in a detached signatures document, so
  2170. * prefix any non-NS-flavored signatures with "additional-signature" rather
  2171. * than "directory-signature". */
  2172. static char *
  2173. networkstatus_format_signatures(networkstatus_t *consensus,
  2174. int for_detached_signatures)
  2175. {
  2176. smartlist_t *elements;
  2177. char buf[4096];
  2178. char *result = NULL;
  2179. int n_sigs = 0;
  2180. const consensus_flavor_t flavor = consensus->flavor;
  2181. const char *flavor_name = networkstatus_get_flavor_name(flavor);
  2182. const char *keyword;
  2183. if (for_detached_signatures && flavor != FLAV_NS)
  2184. keyword = "additional-signature";
  2185. else
  2186. keyword = "directory-signature";
  2187. elements = smartlist_new();
  2188. SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
  2189. SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
  2190. char sk[HEX_DIGEST_LEN+1];
  2191. char id[HEX_DIGEST_LEN+1];
  2192. if (!sig->signature || sig->bad_signature)
  2193. continue;
  2194. ++n_sigs;
  2195. base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
  2196. base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
  2197. if (flavor == FLAV_NS) {
  2198. smartlist_add_asprintf(elements,
  2199. "%s %s %s\n-----BEGIN SIGNATURE-----\n",
  2200. keyword, id, sk);
  2201. } else {
  2202. const char *digest_name =
  2203. crypto_digest_algorithm_get_name(sig->alg);
  2204. smartlist_add_asprintf(elements,
  2205. "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
  2206. keyword,
  2207. for_detached_signatures ? " " : "",
  2208. for_detached_signatures ? flavor_name : "",
  2209. digest_name, id, sk);
  2210. }
  2211. base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
  2212. BASE64_ENCODE_MULTILINE);
  2213. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  2214. smartlist_add(elements, tor_strdup(buf));
  2215. } SMARTLIST_FOREACH_END(sig);
  2216. } SMARTLIST_FOREACH_END(v);
  2217. result = smartlist_join_strings(elements, "", 0, NULL);
  2218. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2219. smartlist_free(elements);
  2220. if (!n_sigs)
  2221. tor_free(result);
  2222. return result;
  2223. }
  2224. /** Return a newly allocated string holding the detached-signatures document
  2225. * corresponding to the signatures on <b>consensuses</b>, which must contain
  2226. * exactly one FLAV_NS consensus, and no more than one consensus for each
  2227. * other flavor. */
  2228. char *
  2229. networkstatus_get_detached_signatures(smartlist_t *consensuses)
  2230. {
  2231. smartlist_t *elements;
  2232. char *result = NULL, *sigs = NULL;
  2233. networkstatus_t *consensus_ns = NULL;
  2234. tor_assert(consensuses);
  2235. SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
  2236. tor_assert(ns);
  2237. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2238. if (ns && ns->flavor == FLAV_NS)
  2239. consensus_ns = ns;
  2240. });
  2241. if (!consensus_ns) {
  2242. log_warn(LD_BUG, "No NS consensus given.");
  2243. return NULL;
  2244. }
  2245. elements = smartlist_new();
  2246. {
  2247. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  2248. vu_buf[ISO_TIME_LEN+1];
  2249. char d[HEX_DIGEST_LEN+1];
  2250. base16_encode(d, sizeof(d),
  2251. consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
  2252. format_iso_time(va_buf, consensus_ns->valid_after);
  2253. format_iso_time(fu_buf, consensus_ns->fresh_until);
  2254. format_iso_time(vu_buf, consensus_ns->valid_until);
  2255. smartlist_add_asprintf(elements,
  2256. "consensus-digest %s\n"
  2257. "valid-after %s\n"
  2258. "fresh-until %s\n"
  2259. "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
  2260. }
  2261. /* Get all the digests for the non-FLAV_NS consensuses */
  2262. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  2263. const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
  2264. int alg;
  2265. if (ns->flavor == FLAV_NS)
  2266. continue;
  2267. /* start with SHA256; we don't include SHA1 for anything but the basic
  2268. * consensus. */
  2269. for (alg = DIGEST_SHA256; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
  2270. char d[HEX_DIGEST256_LEN+1];
  2271. const char *alg_name =
  2272. crypto_digest_algorithm_get_name(alg);
  2273. if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
  2274. continue;
  2275. base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
  2276. smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
  2277. flavor_name, alg_name, d);
  2278. }
  2279. } SMARTLIST_FOREACH_END(ns);
  2280. /* Now get all the sigs for non-FLAV_NS consensuses */
  2281. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  2282. char *sigs_on_this_consensus;
  2283. if (ns->flavor == FLAV_NS)
  2284. continue;
  2285. sigs_on_this_consensus = networkstatus_format_signatures(ns, 1);
  2286. if (!sigs_on_this_consensus) {
  2287. log_warn(LD_DIR, "Couldn't format signatures");
  2288. goto err;
  2289. }
  2290. smartlist_add(elements, sigs_on_this_consensus);
  2291. } SMARTLIST_FOREACH_END(ns);
  2292. /* Now add the FLAV_NS consensus signatrures. */
  2293. sigs = networkstatus_format_signatures(consensus_ns, 1);
  2294. if (!sigs)
  2295. goto err;
  2296. smartlist_add(elements, sigs);
  2297. result = smartlist_join_strings(elements, "", 0, NULL);
  2298. err:
  2299. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2300. smartlist_free(elements);
  2301. return result;
  2302. }
  2303. /** Return a newly allocated string holding a detached-signatures document for
  2304. * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
  2305. * <b>pending</b>. */
  2306. static char *
  2307. get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
  2308. int n_flavors)
  2309. {
  2310. int flav;
  2311. char *signatures;
  2312. smartlist_t *c = smartlist_new();
  2313. for (flav = 0; flav < n_flavors; ++flav) {
  2314. if (pending[flav].consensus)
  2315. smartlist_add(c, pending[flav].consensus);
  2316. }
  2317. signatures = networkstatus_get_detached_signatures(c);
  2318. smartlist_free(c);
  2319. return signatures;
  2320. }
  2321. /** Release all storage held in <b>s</b>. */
  2322. void
  2323. ns_detached_signatures_free(ns_detached_signatures_t *s)
  2324. {
  2325. if (!s)
  2326. return;
  2327. if (s->signatures) {
  2328. STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
  2329. SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
  2330. document_signature_free(sig));
  2331. smartlist_free(sigs);
  2332. } STRMAP_FOREACH_END;
  2333. strmap_free(s->signatures, NULL);
  2334. strmap_free(s->digests, tor_free_);
  2335. }
  2336. tor_free(s);
  2337. }
  2338. /* =====
  2339. * Certificate functions
  2340. * ===== */
  2341. /** Allocate and return a new authority_cert_t with the same contents as
  2342. * <b>cert</b>. */
  2343. authority_cert_t *
  2344. authority_cert_dup(authority_cert_t *cert)
  2345. {
  2346. authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
  2347. tor_assert(cert);
  2348. memcpy(out, cert, sizeof(authority_cert_t));
  2349. /* Now copy pointed-to things. */
  2350. out->cache_info.signed_descriptor_body =
  2351. tor_strndup(cert->cache_info.signed_descriptor_body,
  2352. cert->cache_info.signed_descriptor_len);
  2353. out->cache_info.saved_location = SAVED_NOWHERE;
  2354. out->identity_key = crypto_pk_dup_key(cert->identity_key);
  2355. out->signing_key = crypto_pk_dup_key(cert->signing_key);
  2356. return out;
  2357. }
  2358. /* =====
  2359. * Vote scheduling
  2360. * ===== */
  2361. /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
  2362. * Note that these aren't the intervals we'll use to vote; they're the ones
  2363. * that we'll vote to use. */
  2364. void
  2365. dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
  2366. {
  2367. const or_options_t *options = get_options();
  2368. tor_assert(timing_out);
  2369. timing_out->vote_interval = options->V3AuthVotingInterval;
  2370. timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
  2371. timing_out->vote_delay = options->V3AuthVoteDelay;
  2372. timing_out->dist_delay = options->V3AuthDistDelay;
  2373. }
  2374. /** Return the start of the next interval of size <b>interval</b> (in
  2375. * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
  2376. * starts a fresh interval, and if the last interval of a day would be
  2377. * truncated to less than half its size, it is rolled into the
  2378. * previous interval. */
  2379. time_t
  2380. dirvote_get_start_of_next_interval(time_t now, int interval, int offset)
  2381. {
  2382. struct tm tm;
  2383. time_t midnight_today=0;
  2384. time_t midnight_tomorrow;
  2385. time_t next;
  2386. tor_gmtime_r(&now, &tm);
  2387. tm.tm_hour = 0;
  2388. tm.tm_min = 0;
  2389. tm.tm_sec = 0;
  2390. if (tor_timegm(&tm, &midnight_today) < 0) {
  2391. log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
  2392. }
  2393. midnight_tomorrow = midnight_today + (24*60*60);
  2394. next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
  2395. /* Intervals never cross midnight. */
  2396. if (next > midnight_tomorrow)
  2397. next = midnight_tomorrow;
  2398. /* If the interval would only last half as long as it's supposed to, then
  2399. * skip over to the next day. */
  2400. if (next + interval/2 > midnight_tomorrow)
  2401. next = midnight_tomorrow;
  2402. next += offset;
  2403. if (next - interval > now)
  2404. next -= interval;
  2405. return next;
  2406. }
  2407. /* Using the time <b>now</b>, return the next voting valid-after time. */
  2408. time_t
  2409. get_next_valid_after_time(time_t now)
  2410. {
  2411. time_t next_valid_after_time;
  2412. const or_options_t *options = get_options();
  2413. voting_schedule_t *new_voting_schedule =
  2414. get_voting_schedule(options, now, LOG_INFO);
  2415. tor_assert(new_voting_schedule);
  2416. next_valid_after_time = new_voting_schedule->interval_starts;
  2417. voting_schedule_free(new_voting_schedule);
  2418. return next_valid_after_time;
  2419. }
  2420. static voting_schedule_t voting_schedule;
  2421. /** Set voting_schedule to hold the timing for the next vote we should be
  2422. * doing. */
  2423. void
  2424. dirvote_recalculate_timing(const or_options_t *options, time_t now)
  2425. {
  2426. voting_schedule_t *new_voting_schedule;
  2427. if (!authdir_mode_v3(options)) {
  2428. return;
  2429. }
  2430. /* get the new voting schedule */
  2431. new_voting_schedule = get_voting_schedule(options, now, LOG_NOTICE);
  2432. tor_assert(new_voting_schedule);
  2433. /* Fill in the global static struct now */
  2434. memcpy(&voting_schedule, new_voting_schedule, sizeof(voting_schedule));
  2435. voting_schedule_free(new_voting_schedule);
  2436. }
  2437. /* Populate and return a new voting_schedule_t that can be used to schedule
  2438. * voting. The object is allocated on the heap and it's the responsibility of
  2439. * the caller to free it. Can't fail. */
  2440. voting_schedule_t *
  2441. get_voting_schedule(const or_options_t *options, time_t now, int severity)
  2442. {
  2443. int interval, vote_delay, dist_delay;
  2444. time_t start;
  2445. time_t end;
  2446. networkstatus_t *consensus;
  2447. voting_schedule_t *new_voting_schedule;
  2448. new_voting_schedule = tor_malloc_zero(sizeof(voting_schedule_t));
  2449. consensus = networkstatus_get_live_consensus(now);
  2450. if (consensus) {
  2451. interval = (int)( consensus->fresh_until - consensus->valid_after );
  2452. vote_delay = consensus->vote_seconds;
  2453. dist_delay = consensus->dist_seconds;
  2454. } else {
  2455. interval = options->TestingV3AuthInitialVotingInterval;
  2456. vote_delay = options->TestingV3AuthInitialVoteDelay;
  2457. dist_delay = options->TestingV3AuthInitialDistDelay;
  2458. }
  2459. tor_assert(interval > 0);
  2460. if (vote_delay + dist_delay > interval/2)
  2461. vote_delay = dist_delay = interval / 4;
  2462. start = new_voting_schedule->interval_starts =
  2463. dirvote_get_start_of_next_interval(now,interval,
  2464. options->TestingV3AuthVotingStartOffset);
  2465. end = dirvote_get_start_of_next_interval(start+1, interval,
  2466. options->TestingV3AuthVotingStartOffset);
  2467. tor_assert(end > start);
  2468. new_voting_schedule->fetch_missing_signatures = start - (dist_delay/2);
  2469. new_voting_schedule->voting_ends = start - dist_delay;
  2470. new_voting_schedule->fetch_missing_votes =
  2471. start - dist_delay - (vote_delay/2);
  2472. new_voting_schedule->voting_starts = start - dist_delay - vote_delay;
  2473. {
  2474. char tbuf[ISO_TIME_LEN+1];
  2475. format_iso_time(tbuf, new_voting_schedule->interval_starts);
  2476. tor_log(severity, LD_DIR,"Choosing expected valid-after time as %s: "
  2477. "consensus_set=%d, interval=%d",
  2478. tbuf, consensus?1:0, interval);
  2479. }
  2480. return new_voting_schedule;
  2481. }
  2482. /** Frees a voting_schedule_t. This should be used instead of the generic
  2483. * tor_free. */
  2484. void
  2485. voting_schedule_free(voting_schedule_t *voting_schedule_to_free)
  2486. {
  2487. if (!voting_schedule_to_free)
  2488. return;
  2489. tor_free(voting_schedule_to_free);
  2490. }
  2491. /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
  2492. void
  2493. dirvote_act(const or_options_t *options, time_t now)
  2494. {
  2495. if (!authdir_mode_v3(options))
  2496. return;
  2497. if (!voting_schedule.voting_starts) {
  2498. char *keys = list_v3_auth_ids();
  2499. authority_cert_t *c = get_my_v3_authority_cert();
  2500. log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
  2501. "Mine is %s.",
  2502. keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
  2503. tor_free(keys);
  2504. dirvote_recalculate_timing(options, now);
  2505. }
  2506. if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
  2507. log_notice(LD_DIR, "Time to vote.");
  2508. dirvote_perform_vote();
  2509. voting_schedule.have_voted = 1;
  2510. }
  2511. if (voting_schedule.fetch_missing_votes < now &&
  2512. !voting_schedule.have_fetched_missing_votes) {
  2513. log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
  2514. dirvote_fetch_missing_votes();
  2515. voting_schedule.have_fetched_missing_votes = 1;
  2516. }
  2517. if (voting_schedule.voting_ends < now &&
  2518. !voting_schedule.have_built_consensus) {
  2519. log_notice(LD_DIR, "Time to compute a consensus.");
  2520. dirvote_compute_consensuses();
  2521. /* XXXX We will want to try again later if we haven't got enough
  2522. * votes yet. Implement this if it turns out to ever happen. */
  2523. voting_schedule.have_built_consensus = 1;
  2524. }
  2525. if (voting_schedule.fetch_missing_signatures < now &&
  2526. !voting_schedule.have_fetched_missing_signatures) {
  2527. log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
  2528. dirvote_fetch_missing_signatures();
  2529. voting_schedule.have_fetched_missing_signatures = 1;
  2530. }
  2531. if (voting_schedule.interval_starts < now &&
  2532. !voting_schedule.have_published_consensus) {
  2533. log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
  2534. dirvote_publish_consensus();
  2535. dirvote_clear_votes(0);
  2536. voting_schedule.have_published_consensus = 1;
  2537. /* Update our shared random state with the consensus just published. */
  2538. sr_act_post_consensus(
  2539. networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
  2540. /* XXXX We will want to try again later if we haven't got enough
  2541. * signatures yet. Implement this if it turns out to ever happen. */
  2542. dirvote_recalculate_timing(options, now);
  2543. }
  2544. }
  2545. /** A vote networkstatus_t and its unparsed body: held around so we can
  2546. * use it to generate a consensus (at voting_ends) and so we can serve it to
  2547. * other authorities that might want it. */
  2548. typedef struct pending_vote_t {
  2549. cached_dir_t *vote_body;
  2550. networkstatus_t *vote;
  2551. } pending_vote_t;
  2552. /** List of pending_vote_t for the current vote. Before we've used them to
  2553. * build a consensus, the votes go here. */
  2554. static smartlist_t *pending_vote_list = NULL;
  2555. /** List of pending_vote_t for the previous vote. After we've used them to
  2556. * build a consensus, the votes go here for the next period. */
  2557. static smartlist_t *previous_vote_list = NULL;
  2558. /* DOCDOC pending_consensuses */
  2559. static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
  2560. /** The detached signatures for the consensus that we're currently
  2561. * building. */
  2562. static char *pending_consensus_signatures = NULL;
  2563. /** List of ns_detached_signatures_t: hold signatures that get posted to us
  2564. * before we have generated the consensus on our own. */
  2565. static smartlist_t *pending_consensus_signature_list = NULL;
  2566. /** Generate a networkstatus vote and post it to all the v3 authorities.
  2567. * (V3 Authority only) */
  2568. static int
  2569. dirvote_perform_vote(void)
  2570. {
  2571. crypto_pk_t *key = get_my_v3_authority_signing_key();
  2572. authority_cert_t *cert = get_my_v3_authority_cert();
  2573. networkstatus_t *ns;
  2574. char *contents;
  2575. pending_vote_t *pending_vote;
  2576. time_t now = time(NULL);
  2577. int status;
  2578. const char *msg = "";
  2579. if (!cert || !key) {
  2580. log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
  2581. return -1;
  2582. } else if (cert->expires < now) {
  2583. log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
  2584. return -1;
  2585. }
  2586. if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
  2587. return -1;
  2588. contents = format_networkstatus_vote(key, ns);
  2589. networkstatus_vote_free(ns);
  2590. if (!contents)
  2591. return -1;
  2592. pending_vote = dirvote_add_vote(contents, &msg, &status);
  2593. tor_free(contents);
  2594. if (!pending_vote) {
  2595. log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
  2596. msg);
  2597. return -1;
  2598. }
  2599. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
  2600. ROUTER_PURPOSE_GENERAL,
  2601. V3_DIRINFO,
  2602. pending_vote->vote_body->dir,
  2603. pending_vote->vote_body->dir_len, 0);
  2604. log_notice(LD_DIR, "Vote posted.");
  2605. return 0;
  2606. }
  2607. /** Send an HTTP request to every other v3 authority, for the votes of every
  2608. * authority for which we haven't received a vote yet in this period. (V3
  2609. * authority only) */
  2610. static void
  2611. dirvote_fetch_missing_votes(void)
  2612. {
  2613. smartlist_t *missing_fps = smartlist_new();
  2614. char *resource;
  2615. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  2616. dir_server_t *, ds) {
  2617. if (!(ds->type & V3_DIRINFO))
  2618. continue;
  2619. if (!dirvote_get_vote(ds->v3_identity_digest,
  2620. DGV_BY_ID|DGV_INCLUDE_PENDING)) {
  2621. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  2622. base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
  2623. DIGEST_LEN);
  2624. smartlist_add(missing_fps, cp);
  2625. }
  2626. } SMARTLIST_FOREACH_END(ds);
  2627. if (!smartlist_len(missing_fps)) {
  2628. smartlist_free(missing_fps);
  2629. return;
  2630. }
  2631. {
  2632. char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
  2633. log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
  2634. "Asking every other authority for a copy.",
  2635. smartlist_len(missing_fps), tmp);
  2636. tor_free(tmp);
  2637. }
  2638. resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
  2639. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
  2640. 0, resource);
  2641. tor_free(resource);
  2642. SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
  2643. smartlist_free(missing_fps);
  2644. }
  2645. /** Send a request to every other authority for its detached signatures,
  2646. * unless we have signatures from all other v3 authorities already. */
  2647. static void
  2648. dirvote_fetch_missing_signatures(void)
  2649. {
  2650. int need_any = 0;
  2651. int i;
  2652. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  2653. networkstatus_t *consensus = pending_consensuses[i].consensus;
  2654. if (!consensus ||
  2655. networkstatus_check_consensus_signature(consensus, -1) == 1) {
  2656. /* We have no consensus, or we have one that's signed by everybody. */
  2657. continue;
  2658. }
  2659. need_any = 1;
  2660. }
  2661. if (!need_any)
  2662. return;
  2663. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
  2664. 0, NULL);
  2665. }
  2666. /** Release all storage held by pending consensuses (those waiting for
  2667. * signatures). */
  2668. static void
  2669. dirvote_clear_pending_consensuses(void)
  2670. {
  2671. int i;
  2672. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  2673. pending_consensus_t *pc = &pending_consensuses[i];
  2674. tor_free(pc->body);
  2675. networkstatus_vote_free(pc->consensus);
  2676. pc->consensus = NULL;
  2677. }
  2678. }
  2679. /** Drop all currently pending votes, consensus, and detached signatures. */
  2680. static void
  2681. dirvote_clear_votes(int all_votes)
  2682. {
  2683. if (!previous_vote_list)
  2684. previous_vote_list = smartlist_new();
  2685. if (!pending_vote_list)
  2686. pending_vote_list = smartlist_new();
  2687. /* All "previous" votes are now junk. */
  2688. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
  2689. cached_dir_decref(v->vote_body);
  2690. v->vote_body = NULL;
  2691. networkstatus_vote_free(v->vote);
  2692. tor_free(v);
  2693. });
  2694. smartlist_clear(previous_vote_list);
  2695. if (all_votes) {
  2696. /* If we're dumping all the votes, we delete the pending ones. */
  2697. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  2698. cached_dir_decref(v->vote_body);
  2699. v->vote_body = NULL;
  2700. networkstatus_vote_free(v->vote);
  2701. tor_free(v);
  2702. });
  2703. } else {
  2704. /* Otherwise, we move them into "previous". */
  2705. smartlist_add_all(previous_vote_list, pending_vote_list);
  2706. }
  2707. smartlist_clear(pending_vote_list);
  2708. if (pending_consensus_signature_list) {
  2709. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
  2710. tor_free(cp));
  2711. smartlist_clear(pending_consensus_signature_list);
  2712. }
  2713. tor_free(pending_consensus_signatures);
  2714. dirvote_clear_pending_consensuses();
  2715. }
  2716. /** Return a newly allocated string containing the hex-encoded v3 authority
  2717. identity digest of every recognized v3 authority. */
  2718. static char *
  2719. list_v3_auth_ids(void)
  2720. {
  2721. smartlist_t *known_v3_keys = smartlist_new();
  2722. char *keys;
  2723. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  2724. dir_server_t *, ds,
  2725. if ((ds->type & V3_DIRINFO) &&
  2726. !tor_digest_is_zero(ds->v3_identity_digest))
  2727. smartlist_add(known_v3_keys,
  2728. tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
  2729. keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
  2730. SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
  2731. smartlist_free(known_v3_keys);
  2732. return keys;
  2733. }
  2734. /** Called when we have received a networkstatus vote in <b>vote_body</b>.
  2735. * Parse and validate it, and on success store it as a pending vote (which we
  2736. * then return). Return NULL on failure. Sets *<b>msg_out</b> and
  2737. * *<b>status_out</b> to an HTTP response and status code. (V3 authority
  2738. * only) */
  2739. pending_vote_t *
  2740. dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
  2741. {
  2742. networkstatus_t *vote;
  2743. networkstatus_voter_info_t *vi;
  2744. dir_server_t *ds;
  2745. pending_vote_t *pending_vote = NULL;
  2746. const char *end_of_vote = NULL;
  2747. int any_failed = 0;
  2748. tor_assert(vote_body);
  2749. tor_assert(msg_out);
  2750. tor_assert(status_out);
  2751. if (!pending_vote_list)
  2752. pending_vote_list = smartlist_new();
  2753. *status_out = 0;
  2754. *msg_out = NULL;
  2755. again:
  2756. vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
  2757. NS_TYPE_VOTE);
  2758. if (!end_of_vote)
  2759. end_of_vote = vote_body + strlen(vote_body);
  2760. if (!vote) {
  2761. log_warn(LD_DIR, "Couldn't parse vote: length was %d",
  2762. (int)strlen(vote_body));
  2763. *msg_out = "Unable to parse vote";
  2764. goto err;
  2765. }
  2766. tor_assert(smartlist_len(vote->voters) == 1);
  2767. vi = get_voter(vote);
  2768. {
  2769. int any_sig_good = 0;
  2770. SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
  2771. if (sig->good_signature)
  2772. any_sig_good = 1);
  2773. tor_assert(any_sig_good);
  2774. }
  2775. ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
  2776. if (!ds) {
  2777. char *keys = list_v3_auth_ids();
  2778. log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
  2779. "with authority key ID %s. "
  2780. "This key ID is not recognized. Known v3 key IDs are: %s",
  2781. vi->nickname, vi->address,
  2782. hex_str(vi->identity_digest, DIGEST_LEN), keys);
  2783. tor_free(keys);
  2784. *msg_out = "Vote not from a recognized v3 authority";
  2785. goto err;
  2786. }
  2787. tor_assert(vote->cert);
  2788. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  2789. vote->cert->signing_key_digest)) {
  2790. /* Hey, it's a new cert! */
  2791. trusted_dirs_load_certs_from_string(
  2792. vote->cert->cache_info.signed_descriptor_body,
  2793. TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/,
  2794. NULL);
  2795. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  2796. vote->cert->signing_key_digest)) {
  2797. log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
  2798. }
  2799. }
  2800. /* Is it for the right period? */
  2801. if (vote->valid_after != voting_schedule.interval_starts) {
  2802. char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
  2803. format_iso_time(tbuf1, vote->valid_after);
  2804. format_iso_time(tbuf2, voting_schedule.interval_starts);
  2805. log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
  2806. "we were expecting %s", vi->address, tbuf1, tbuf2);
  2807. *msg_out = "Bad valid-after time";
  2808. goto err;
  2809. }
  2810. /* Fetch any new router descriptors we just learned about */
  2811. update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
  2812. /* Now see whether we already have a vote from this authority. */
  2813. SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
  2814. if (fast_memeq(v->vote->cert->cache_info.identity_digest,
  2815. vote->cert->cache_info.identity_digest,
  2816. DIGEST_LEN)) {
  2817. networkstatus_voter_info_t *vi_old = get_voter(v->vote);
  2818. if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
  2819. /* Ah, it's the same vote. Not a problem. */
  2820. log_info(LD_DIR, "Discarding a vote we already have (from %s).",
  2821. vi->address);
  2822. if (*status_out < 200)
  2823. *status_out = 200;
  2824. goto discard;
  2825. } else if (v->vote->published < vote->published) {
  2826. log_notice(LD_DIR, "Replacing an older pending vote from this "
  2827. "directory (%s)", vi->address);
  2828. cached_dir_decref(v->vote_body);
  2829. networkstatus_vote_free(v->vote);
  2830. v->vote_body = new_cached_dir(tor_strndup(vote_body,
  2831. end_of_vote-vote_body),
  2832. vote->published);
  2833. v->vote = vote;
  2834. if (end_of_vote &&
  2835. !strcmpstart(end_of_vote, "network-status-version"))
  2836. goto again;
  2837. if (*status_out < 200)
  2838. *status_out = 200;
  2839. if (!*msg_out)
  2840. *msg_out = "OK";
  2841. return v;
  2842. } else {
  2843. *msg_out = "Already have a newer pending vote";
  2844. goto err;
  2845. }
  2846. }
  2847. } SMARTLIST_FOREACH_END(v);
  2848. /* This a valid vote, update our shared random state. */
  2849. sr_handle_received_commits(vote->sr_info.commits,
  2850. vote->cert->identity_key);
  2851. pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
  2852. pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
  2853. end_of_vote-vote_body),
  2854. vote->published);
  2855. pending_vote->vote = vote;
  2856. smartlist_add(pending_vote_list, pending_vote);
  2857. if (!strcmpstart(end_of_vote, "network-status-version ")) {
  2858. vote_body = end_of_vote;
  2859. goto again;
  2860. }
  2861. goto done;
  2862. err:
  2863. any_failed = 1;
  2864. if (!*msg_out)
  2865. *msg_out = "Error adding vote";
  2866. if (*status_out < 400)
  2867. *status_out = 400;
  2868. discard:
  2869. networkstatus_vote_free(vote);
  2870. if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
  2871. vote_body = end_of_vote;
  2872. goto again;
  2873. }
  2874. done:
  2875. if (*status_out < 200)
  2876. *status_out = 200;
  2877. if (!*msg_out) {
  2878. if (!any_failed && !pending_vote) {
  2879. *msg_out = "Duplicate discarded";
  2880. } else {
  2881. *msg_out = "ok";
  2882. }
  2883. }
  2884. return any_failed ? NULL : pending_vote;
  2885. }
  2886. /* Write the votes in <b>pending_vote_list</b> to disk. */
  2887. static void
  2888. write_v3_votes_to_disk(const smartlist_t *pending_votes)
  2889. {
  2890. smartlist_t *votestrings = smartlist_new();
  2891. char *votefile = NULL;
  2892. SMARTLIST_FOREACH(pending_votes, pending_vote_t *, v,
  2893. {
  2894. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  2895. c->bytes = v->vote_body->dir;
  2896. c->len = v->vote_body->dir_len;
  2897. smartlist_add(votestrings, c); /* collect strings to write to disk */
  2898. });
  2899. votefile = get_datadir_fname("v3-status-votes");
  2900. write_chunks_to_file(votefile, votestrings, 0, 0);
  2901. log_debug(LD_DIR, "Wrote votes to disk (%s)!", votefile);
  2902. tor_free(votefile);
  2903. SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
  2904. smartlist_free(votestrings);
  2905. }
  2906. /** Try to compute a v3 networkstatus consensus from the currently pending
  2907. * votes. Return 0 on success, -1 on failure. Store the consensus in
  2908. * pending_consensus: it won't be ready to be published until we have
  2909. * everybody else's signatures collected too. (V3 Authority only) */
  2910. static int
  2911. dirvote_compute_consensuses(void)
  2912. {
  2913. /* Have we got enough votes to try? */
  2914. int n_votes, n_voters, n_vote_running = 0;
  2915. smartlist_t *votes = NULL;
  2916. char *consensus_body = NULL, *signatures = NULL;
  2917. networkstatus_t *consensus = NULL;
  2918. authority_cert_t *my_cert;
  2919. pending_consensus_t pending[N_CONSENSUS_FLAVORS];
  2920. int flav;
  2921. memset(pending, 0, sizeof(pending));
  2922. if (!pending_vote_list)
  2923. pending_vote_list = smartlist_new();
  2924. /* Write votes to disk */
  2925. write_v3_votes_to_disk(pending_vote_list);
  2926. /* Setup votes smartlist */
  2927. votes = smartlist_new();
  2928. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
  2929. {
  2930. smartlist_add(votes, v->vote); /* collect votes to compute consensus */
  2931. });
  2932. /* See if consensus managed to achieve majority */
  2933. n_voters = get_n_authorities(V3_DIRINFO);
  2934. n_votes = smartlist_len(pending_vote_list);
  2935. if (n_votes <= n_voters/2) {
  2936. log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
  2937. "%d of %d", n_votes, n_voters/2+1);
  2938. goto err;
  2939. }
  2940. tor_assert(pending_vote_list);
  2941. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  2942. if (smartlist_contains_string(v->vote->known_flags, "Running"))
  2943. n_vote_running++;
  2944. });
  2945. if (!n_vote_running) {
  2946. /* See task 1066. */
  2947. log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
  2948. "and publishing a consensus without Running nodes "
  2949. "would make many clients stop working. Not "
  2950. "generating a consensus!");
  2951. goto err;
  2952. }
  2953. if (!(my_cert = get_my_v3_authority_cert())) {
  2954. log_warn(LD_DIR, "Can't generate consensus without a certificate.");
  2955. goto err;
  2956. }
  2957. {
  2958. char legacy_dbuf[DIGEST_LEN];
  2959. crypto_pk_t *legacy_sign=NULL;
  2960. char *legacy_id_digest = NULL;
  2961. int n_generated = 0;
  2962. if (get_options()->V3AuthUseLegacyKey) {
  2963. authority_cert_t *cert = get_my_v3_legacy_cert();
  2964. legacy_sign = get_my_v3_legacy_signing_key();
  2965. if (cert) {
  2966. if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
  2967. log_warn(LD_BUG,
  2968. "Unable to compute digest of legacy v3 identity key");
  2969. } else {
  2970. legacy_id_digest = legacy_dbuf;
  2971. }
  2972. }
  2973. }
  2974. for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  2975. const char *flavor_name = networkstatus_get_flavor_name(flav);
  2976. consensus_body = networkstatus_compute_consensus(
  2977. votes, n_voters,
  2978. my_cert->identity_key,
  2979. get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
  2980. flav);
  2981. if (!consensus_body) {
  2982. log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
  2983. flavor_name);
  2984. continue;
  2985. }
  2986. consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
  2987. NS_TYPE_CONSENSUS);
  2988. if (!consensus) {
  2989. log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
  2990. flavor_name);
  2991. tor_free(consensus_body);
  2992. continue;
  2993. }
  2994. /* 'Check' our own signature, to mark it valid. */
  2995. networkstatus_check_consensus_signature(consensus, -1);
  2996. pending[flav].body = consensus_body;
  2997. pending[flav].consensus = consensus;
  2998. n_generated++;
  2999. consensus_body = NULL;
  3000. consensus = NULL;
  3001. }
  3002. if (!n_generated) {
  3003. log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
  3004. goto err;
  3005. }
  3006. }
  3007. signatures = get_detached_signatures_from_pending_consensuses(
  3008. pending, N_CONSENSUS_FLAVORS);
  3009. if (!signatures) {
  3010. log_warn(LD_DIR, "Couldn't extract signatures.");
  3011. goto err;
  3012. }
  3013. dirvote_clear_pending_consensuses();
  3014. memcpy(pending_consensuses, pending, sizeof(pending));
  3015. tor_free(pending_consensus_signatures);
  3016. pending_consensus_signatures = signatures;
  3017. if (pending_consensus_signature_list) {
  3018. int n_sigs = 0;
  3019. /* we may have gotten signatures for this consensus before we built
  3020. * it ourself. Add them now. */
  3021. SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
  3022. const char *msg = NULL;
  3023. int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
  3024. "pending", &msg);
  3025. if (r >= 0)
  3026. n_sigs += r;
  3027. else
  3028. log_warn(LD_DIR,
  3029. "Could not add queued signature to new consensus: %s",
  3030. msg);
  3031. tor_free(sig);
  3032. } SMARTLIST_FOREACH_END(sig);
  3033. if (n_sigs)
  3034. log_notice(LD_DIR, "Added %d pending signatures while building "
  3035. "consensus.", n_sigs);
  3036. smartlist_clear(pending_consensus_signature_list);
  3037. }
  3038. log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
  3039. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
  3040. ROUTER_PURPOSE_GENERAL,
  3041. V3_DIRINFO,
  3042. pending_consensus_signatures,
  3043. strlen(pending_consensus_signatures), 0);
  3044. log_notice(LD_DIR, "Signature(s) posted.");
  3045. smartlist_free(votes);
  3046. return 0;
  3047. err:
  3048. smartlist_free(votes);
  3049. tor_free(consensus_body);
  3050. tor_free(signatures);
  3051. networkstatus_vote_free(consensus);
  3052. return -1;
  3053. }
  3054. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  3055. * signatures on the currently pending consensus. Add them to <b>pc</b>
  3056. * as appropriate. Return the number of signatures added. (?) */
  3057. static int
  3058. dirvote_add_signatures_to_pending_consensus(
  3059. pending_consensus_t *pc,
  3060. ns_detached_signatures_t *sigs,
  3061. const char *source,
  3062. int severity,
  3063. const char **msg_out)
  3064. {
  3065. const char *flavor_name;
  3066. int r = -1;
  3067. /* Only call if we have a pending consensus right now. */
  3068. tor_assert(pc->consensus);
  3069. tor_assert(pc->body);
  3070. tor_assert(pending_consensus_signatures);
  3071. flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
  3072. *msg_out = NULL;
  3073. {
  3074. smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
  3075. log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
  3076. sig_list ? smartlist_len(sig_list) : 0, flavor_name);
  3077. }
  3078. r = networkstatus_add_detached_signatures(pc->consensus, sigs,
  3079. source, severity, msg_out);
  3080. log_info(LD_DIR,"Added %d signatures to consensus.", r);
  3081. if (r >= 1) {
  3082. char *new_signatures =
  3083. networkstatus_format_signatures(pc->consensus, 0);
  3084. char *dst, *dst_end;
  3085. size_t new_consensus_len;
  3086. if (!new_signatures) {
  3087. *msg_out = "No signatures to add";
  3088. goto err;
  3089. }
  3090. new_consensus_len =
  3091. strlen(pc->body) + strlen(new_signatures) + 1;
  3092. pc->body = tor_realloc(pc->body, new_consensus_len);
  3093. dst_end = pc->body + new_consensus_len;
  3094. dst = strstr(pc->body, "directory-signature ");
  3095. tor_assert(dst);
  3096. strlcpy(dst, new_signatures, dst_end-dst);
  3097. /* We remove this block once it has failed to crash for a while. But
  3098. * unless it shows up in profiles, we're probably better leaving it in,
  3099. * just in case we break detached signature processing at some point. */
  3100. {
  3101. networkstatus_t *v = networkstatus_parse_vote_from_string(
  3102. pc->body, NULL,
  3103. NS_TYPE_CONSENSUS);
  3104. tor_assert(v);
  3105. networkstatus_vote_free(v);
  3106. }
  3107. *msg_out = "Signatures added";
  3108. tor_free(new_signatures);
  3109. } else if (r == 0) {
  3110. *msg_out = "Signatures ignored";
  3111. } else {
  3112. goto err;
  3113. }
  3114. goto done;
  3115. err:
  3116. if (!*msg_out)
  3117. *msg_out = "Unrecognized error while adding detached signatures.";
  3118. done:
  3119. return r;
  3120. }
  3121. static int
  3122. dirvote_add_signatures_to_all_pending_consensuses(
  3123. const char *detached_signatures_body,
  3124. const char *source,
  3125. const char **msg_out)
  3126. {
  3127. int r=0, i, n_added = 0, errors = 0;
  3128. ns_detached_signatures_t *sigs;
  3129. tor_assert(detached_signatures_body);
  3130. tor_assert(msg_out);
  3131. tor_assert(pending_consensus_signatures);
  3132. if (!(sigs = networkstatus_parse_detached_signatures(
  3133. detached_signatures_body, NULL))) {
  3134. *msg_out = "Couldn't parse detached signatures.";
  3135. goto err;
  3136. }
  3137. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  3138. int res;
  3139. int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
  3140. pending_consensus_t *pc = &pending_consensuses[i];
  3141. if (!pc->consensus)
  3142. continue;
  3143. res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
  3144. severity, msg_out);
  3145. if (res < 0)
  3146. errors++;
  3147. else
  3148. n_added += res;
  3149. }
  3150. if (errors && !n_added) {
  3151. r = -1;
  3152. goto err;
  3153. }
  3154. if (n_added && pending_consensuses[FLAV_NS].consensus) {
  3155. char *new_detached =
  3156. get_detached_signatures_from_pending_consensuses(
  3157. pending_consensuses, N_CONSENSUS_FLAVORS);
  3158. if (new_detached) {
  3159. tor_free(pending_consensus_signatures);
  3160. pending_consensus_signatures = new_detached;
  3161. }
  3162. }
  3163. r = n_added;
  3164. goto done;
  3165. err:
  3166. if (!*msg_out)
  3167. *msg_out = "Unrecognized error while adding detached signatures.";
  3168. done:
  3169. ns_detached_signatures_free(sigs);
  3170. /* XXXX NM Check how return is used. We can now have an error *and*
  3171. signatures added. */
  3172. return r;
  3173. }
  3174. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  3175. * signatures on the currently pending consensus. Add them to the pending
  3176. * consensus (if we have one); otherwise queue them until we have a
  3177. * consensus. Return negative on failure, nonnegative on success. */
  3178. int
  3179. dirvote_add_signatures(const char *detached_signatures_body,
  3180. const char *source,
  3181. const char **msg)
  3182. {
  3183. if (pending_consensuses[FLAV_NS].consensus) {
  3184. log_notice(LD_DIR, "Got a signature from %s. "
  3185. "Adding it to the pending consensus.", source);
  3186. return dirvote_add_signatures_to_all_pending_consensuses(
  3187. detached_signatures_body, source, msg);
  3188. } else {
  3189. log_notice(LD_DIR, "Got a signature from %s. "
  3190. "Queuing it for the next consensus.", source);
  3191. if (!pending_consensus_signature_list)
  3192. pending_consensus_signature_list = smartlist_new();
  3193. smartlist_add(pending_consensus_signature_list,
  3194. tor_strdup(detached_signatures_body));
  3195. *msg = "Signature queued";
  3196. return 0;
  3197. }
  3198. }
  3199. /** Replace the consensus that we're currently serving with the one that we've
  3200. * been building. (V3 Authority only) */
  3201. static int
  3202. dirvote_publish_consensus(void)
  3203. {
  3204. int i;
  3205. /* Now remember all the other consensuses as if we were a directory cache. */
  3206. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  3207. pending_consensus_t *pending = &pending_consensuses[i];
  3208. const char *name;
  3209. name = networkstatus_get_flavor_name(i);
  3210. tor_assert(name);
  3211. if (!pending->consensus ||
  3212. networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
  3213. log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
  3214. continue;
  3215. }
  3216. if (networkstatus_set_current_consensus(pending->body, name, 0, NULL))
  3217. log_warn(LD_DIR, "Error publishing %s consensus", name);
  3218. else
  3219. log_notice(LD_DIR, "Published %s consensus", name);
  3220. }
  3221. return 0;
  3222. }
  3223. /** Release all static storage held in dirvote.c */
  3224. void
  3225. dirvote_free_all(void)
  3226. {
  3227. dirvote_clear_votes(1);
  3228. /* now empty as a result of dirvote_clear_votes(). */
  3229. smartlist_free(pending_vote_list);
  3230. pending_vote_list = NULL;
  3231. smartlist_free(previous_vote_list);
  3232. previous_vote_list = NULL;
  3233. dirvote_clear_pending_consensuses();
  3234. tor_free(pending_consensus_signatures);
  3235. if (pending_consensus_signature_list) {
  3236. /* now empty as a result of dirvote_clear_votes(). */
  3237. smartlist_free(pending_consensus_signature_list);
  3238. pending_consensus_signature_list = NULL;
  3239. }
  3240. }
  3241. /* ====
  3242. * Access to pending items.
  3243. * ==== */
  3244. /** Return the body of the consensus that we're currently trying to build. */
  3245. MOCK_IMPL(const char *,
  3246. dirvote_get_pending_consensus, (consensus_flavor_t flav))
  3247. {
  3248. tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
  3249. return pending_consensuses[flav].body;
  3250. }
  3251. /** Return the signatures that we know for the consensus that we're currently
  3252. * trying to build. */
  3253. MOCK_IMPL(const char *,
  3254. dirvote_get_pending_detached_signatures, (void))
  3255. {
  3256. return pending_consensus_signatures;
  3257. }
  3258. /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
  3259. * vote for the authority with the v3 authority identity key digest <b>fp</b>;
  3260. * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
  3261. * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
  3262. * false, do not consider any votes for a consensus that's already been built.
  3263. * If <b>include_pending</b> is false, do not consider any votes for the
  3264. * consensus that's in progress. May return NULL if we have no vote for the
  3265. * authority in question. */
  3266. const cached_dir_t *
  3267. dirvote_get_vote(const char *fp, int flags)
  3268. {
  3269. int by_id = flags & DGV_BY_ID;
  3270. const int include_pending = flags & DGV_INCLUDE_PENDING;
  3271. const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
  3272. if (!pending_vote_list && !previous_vote_list)
  3273. return NULL;
  3274. if (fp == NULL) {
  3275. authority_cert_t *c = get_my_v3_authority_cert();
  3276. if (c) {
  3277. fp = c->cache_info.identity_digest;
  3278. by_id = 1;
  3279. } else
  3280. return NULL;
  3281. }
  3282. if (by_id) {
  3283. if (pending_vote_list && include_pending) {
  3284. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  3285. if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  3286. return pv->vote_body);
  3287. }
  3288. if (previous_vote_list && include_previous) {
  3289. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  3290. if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  3291. return pv->vote_body);
  3292. }
  3293. } else {
  3294. if (pending_vote_list && include_pending) {
  3295. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  3296. if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  3297. return pv->vote_body);
  3298. }
  3299. if (previous_vote_list && include_previous) {
  3300. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  3301. if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  3302. return pv->vote_body);
  3303. }
  3304. }
  3305. return NULL;
  3306. }
  3307. /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
  3308. * according to <b>consensus_method</b>.
  3309. **/
  3310. microdesc_t *
  3311. dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
  3312. {
  3313. microdesc_t *result = NULL;
  3314. char *key = NULL, *summary = NULL, *family = NULL;
  3315. size_t keylen;
  3316. smartlist_t *chunks = smartlist_new();
  3317. char *output = NULL;
  3318. if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
  3319. goto done;
  3320. summary = policy_summarize(ri->exit_policy, AF_INET);
  3321. if (ri->declared_family)
  3322. family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
  3323. smartlist_add_asprintf(chunks, "onion-key\n%s", key);
  3324. if (consensus_method >= MIN_METHOD_FOR_NTOR_KEY &&
  3325. ri->onion_curve25519_pkey) {
  3326. char kbuf[128];
  3327. base64_encode(kbuf, sizeof(kbuf),
  3328. (const char*)ri->onion_curve25519_pkey->public_key,
  3329. CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
  3330. smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
  3331. }
  3332. if (consensus_method >= MIN_METHOD_FOR_A_LINES &&
  3333. !tor_addr_is_null(&ri->ipv6_addr) && ri->ipv6_orport)
  3334. smartlist_add_asprintf(chunks, "a %s\n",
  3335. fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
  3336. if (family)
  3337. smartlist_add_asprintf(chunks, "family %s\n", family);
  3338. if (summary && strcmp(summary, "reject 1-65535"))
  3339. smartlist_add_asprintf(chunks, "p %s\n", summary);
  3340. if (consensus_method >= MIN_METHOD_FOR_P6_LINES &&
  3341. ri->ipv6_exit_policy) {
  3342. /* XXXX+++ This doesn't match proposal 208, which says these should
  3343. * be taken unchanged from the routerinfo. That's bogosity, IMO:
  3344. * the proposal should have said to do this instead.*/
  3345. char *p6 = write_short_policy(ri->ipv6_exit_policy);
  3346. if (p6 && strcmp(p6, "reject 1-65535"))
  3347. smartlist_add_asprintf(chunks, "p6 %s\n", p6);
  3348. tor_free(p6);
  3349. }
  3350. if (consensus_method >= MIN_METHOD_FOR_ID_HASH_IN_MD) {
  3351. char idbuf[ED25519_BASE64_LEN+1];
  3352. const char *keytype;
  3353. if (consensus_method >= MIN_METHOD_FOR_ED25519_ID_IN_MD &&
  3354. ri->cache_info.signing_key_cert &&
  3355. ri->cache_info.signing_key_cert->signing_key_included) {
  3356. keytype = "ed25519";
  3357. ed25519_public_to_base64(idbuf,
  3358. &ri->cache_info.signing_key_cert->signing_key);
  3359. } else {
  3360. keytype = "rsa1024";
  3361. digest_to_base64(idbuf, ri->cache_info.identity_digest);
  3362. }
  3363. smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
  3364. }
  3365. output = smartlist_join_strings(chunks, "", 0, NULL);
  3366. {
  3367. smartlist_t *lst = microdescs_parse_from_string(output,
  3368. output+strlen(output), 0,
  3369. SAVED_NOWHERE, NULL);
  3370. if (smartlist_len(lst) != 1) {
  3371. log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
  3372. SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
  3373. smartlist_free(lst);
  3374. goto done;
  3375. }
  3376. result = smartlist_get(lst, 0);
  3377. smartlist_free(lst);
  3378. }
  3379. done:
  3380. tor_free(output);
  3381. tor_free(key);
  3382. tor_free(summary);
  3383. tor_free(family);
  3384. if (chunks) {
  3385. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  3386. smartlist_free(chunks);
  3387. }
  3388. return result;
  3389. }
  3390. /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
  3391. * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
  3392. * in <b>out</b>. Return -1 on failure and the number of characters written
  3393. * on success. */
  3394. ssize_t
  3395. dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
  3396. const microdesc_t *md,
  3397. int consensus_method_low,
  3398. int consensus_method_high)
  3399. {
  3400. ssize_t ret = -1;
  3401. char d64[BASE64_DIGEST256_LEN+1];
  3402. char *microdesc_consensus_methods =
  3403. make_consensus_method_list(consensus_method_low,
  3404. consensus_method_high,
  3405. ",");
  3406. tor_assert(microdesc_consensus_methods);
  3407. if (digest256_to_base64(d64, md->digest)<0)
  3408. goto out;
  3409. if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
  3410. microdesc_consensus_methods, d64)<0)
  3411. goto out;
  3412. ret = strlen(out_buf);
  3413. out:
  3414. tor_free(microdesc_consensus_methods);
  3415. return ret;
  3416. }
  3417. /** Array of start and end of consensus methods used for supported
  3418. microdescriptor formats. */
  3419. static const struct consensus_method_range_t {
  3420. int low;
  3421. int high;
  3422. } microdesc_consensus_methods[] = {
  3423. {MIN_SUPPORTED_CONSENSUS_METHOD, MIN_METHOD_FOR_A_LINES - 1},
  3424. {MIN_METHOD_FOR_A_LINES, MIN_METHOD_FOR_P6_LINES - 1},
  3425. {MIN_METHOD_FOR_P6_LINES, MIN_METHOD_FOR_NTOR_KEY - 1},
  3426. {MIN_METHOD_FOR_NTOR_KEY, MIN_METHOD_FOR_ID_HASH_IN_MD - 1},
  3427. {MIN_METHOD_FOR_ID_HASH_IN_MD, MIN_METHOD_FOR_ED25519_ID_IN_MD - 1},
  3428. {MIN_METHOD_FOR_ED25519_ID_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
  3429. {-1, -1}
  3430. };
  3431. /** Helper type used when generating the microdescriptor lines in a directory
  3432. * vote. */
  3433. typedef struct microdesc_vote_line_t {
  3434. int low;
  3435. int high;
  3436. microdesc_t *md;
  3437. struct microdesc_vote_line_t *next;
  3438. } microdesc_vote_line_t;
  3439. /** Generate and return a linked list of all the lines that should appear to
  3440. * describe a router's microdescriptor versions in a directory vote.
  3441. * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
  3442. vote_microdesc_hash_t *
  3443. dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now,
  3444. smartlist_t *microdescriptors_out)
  3445. {
  3446. const struct consensus_method_range_t *cmr;
  3447. microdesc_vote_line_t *entries = NULL, *ep;
  3448. vote_microdesc_hash_t *result = NULL;
  3449. /* Generate the microdescriptors. */
  3450. for (cmr = microdesc_consensus_methods;
  3451. cmr->low != -1 && cmr->high != -1;
  3452. cmr++) {
  3453. microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
  3454. if (md) {
  3455. microdesc_vote_line_t *e =
  3456. tor_malloc_zero(sizeof(microdesc_vote_line_t));
  3457. e->md = md;
  3458. e->low = cmr->low;
  3459. e->high = cmr->high;
  3460. e->next = entries;
  3461. entries = e;
  3462. }
  3463. }
  3464. /* Compress adjacent identical ones */
  3465. for (ep = entries; ep; ep = ep->next) {
  3466. while (ep->next &&
  3467. fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
  3468. ep->low == ep->next->high + 1) {
  3469. microdesc_vote_line_t *next = ep->next;
  3470. ep->low = next->low;
  3471. microdesc_free(next->md);
  3472. ep->next = next->next;
  3473. tor_free(next);
  3474. }
  3475. }
  3476. /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
  3477. while ((ep = entries)) {
  3478. char buf[128];
  3479. vote_microdesc_hash_t *h;
  3480. dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
  3481. ep->low, ep->high);
  3482. h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
  3483. h->microdesc_hash_line = tor_strdup(buf);
  3484. h->next = result;
  3485. result = h;
  3486. ep->md->last_listed = now;
  3487. smartlist_add(microdescriptors_out, ep->md);
  3488. entries = ep->next;
  3489. tor_free(ep);
  3490. }
  3491. return result;
  3492. }
  3493. /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
  3494. * the digest algorithm <b>alg</b>, decode it and copy it into
  3495. * <b>digest256_out</b> and return 0. Otherwise return -1. */
  3496. int
  3497. vote_routerstatus_find_microdesc_hash(char *digest256_out,
  3498. const vote_routerstatus_t *vrs,
  3499. int method,
  3500. digest_algorithm_t alg)
  3501. {
  3502. /* XXXX only returns the sha256 method. */
  3503. const vote_microdesc_hash_t *h;
  3504. char mstr[64];
  3505. size_t mlen;
  3506. char dstr[64];
  3507. tor_snprintf(mstr, sizeof(mstr), "%d", method);
  3508. mlen = strlen(mstr);
  3509. tor_snprintf(dstr, sizeof(dstr), " %s=",
  3510. crypto_digest_algorithm_get_name(alg));
  3511. for (h = vrs->microdesc; h; h = h->next) {
  3512. const char *cp = h->microdesc_hash_line;
  3513. size_t num_len;
  3514. /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
  3515. * the first part. */
  3516. while (1) {
  3517. num_len = strspn(cp, "1234567890");
  3518. if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
  3519. /* This is the line. */
  3520. char buf[BASE64_DIGEST256_LEN+1];
  3521. /* XXXX ignores extraneous stuff if the digest is too long. This
  3522. * seems harmless enough, right? */
  3523. cp = strstr(cp, dstr);
  3524. if (!cp)
  3525. return -1;
  3526. cp += strlen(dstr);
  3527. strlcpy(buf, cp, sizeof(buf));
  3528. return digest256_from_base64(digest256_out, buf);
  3529. }
  3530. if (num_len == 0 || cp[num_len] != ',')
  3531. break;
  3532. cp += num_len + 1;
  3533. }
  3534. }
  3535. return -1;
  3536. }