dirvote.c 120 KB

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