dirvote.c 114 KB

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