dirvote.c 140 KB

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