dirvote.c 125 KB

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