dirvote.c 132 KB

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