dirvote.c 159 KB

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