dirvote.c 123 KB

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