dirvote.c 126 KB

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