dirvote.c 128 KB

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