dirvote.c 158 KB

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