dirvote.c 137 KB

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