dirvote.c 127 KB

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