dirvote.c 138 KB

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