dirvote.c 132 KB

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