dirvote.c 124 KB

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