dirvote.c 120 KB

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