dirvote.c 114 KB

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