dirvote.c 131 KB

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