dirvote.c 139 KB

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