dirvote.c 128 KB

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