dirvote.c 120 KB

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