dirvote.c 159 KB

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