dirvote.c 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729
  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) < 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. #define DEFAULT_MAX_UNMEASURED_BW 20
  1275. uint32_t max_unmeasured_bw = DEFAULT_MAX_UNMEASURED_BW;
  1276. int64_t G=0, M=0, E=0, D=0, T=0; /* For bandwidth weights */
  1277. const routerstatus_format_type_t rs_format =
  1278. flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
  1279. char *params = NULL;
  1280. int added_weights = 0;
  1281. tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
  1282. tor_assert(total_authorities >= smartlist_len(votes));
  1283. flavor_name = networkstatus_get_flavor_name(flavor);
  1284. if (!smartlist_len(votes)) {
  1285. log_warn(LD_DIR, "Can't compute a consensus from no votes.");
  1286. return NULL;
  1287. }
  1288. flags = smartlist_new();
  1289. consensus_method = compute_consensus_method(votes);
  1290. if (consensus_method_is_supported(consensus_method)) {
  1291. log_info(LD_DIR, "Generating consensus using method %d.",
  1292. consensus_method);
  1293. } else {
  1294. log_warn(LD_DIR, "The other authorities will use consensus method %d, "
  1295. "which I don't support. Maybe I should upgrade!",
  1296. consensus_method);
  1297. consensus_method = 1;
  1298. }
  1299. /* Compute medians of time-related things, and figure out how many
  1300. * routers we might need to talk about. */
  1301. {
  1302. int n_votes = smartlist_len(votes);
  1303. time_t *va_times = tor_malloc(n_votes * sizeof(time_t));
  1304. time_t *fu_times = tor_malloc(n_votes * sizeof(time_t));
  1305. time_t *vu_times = tor_malloc(n_votes * sizeof(time_t));
  1306. int *votesec_list = tor_malloc(n_votes * sizeof(int));
  1307. int *distsec_list = tor_malloc(n_votes * sizeof(int));
  1308. int n_versioning_clients = 0, n_versioning_servers = 0;
  1309. smartlist_t *combined_client_versions = smartlist_new();
  1310. smartlist_t *combined_server_versions = smartlist_new();
  1311. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1312. tor_assert(v->type == NS_TYPE_VOTE);
  1313. va_times[v_sl_idx] = v->valid_after;
  1314. fu_times[v_sl_idx] = v->fresh_until;
  1315. vu_times[v_sl_idx] = v->valid_until;
  1316. votesec_list[v_sl_idx] = v->vote_seconds;
  1317. distsec_list[v_sl_idx] = v->dist_seconds;
  1318. if (v->client_versions) {
  1319. smartlist_t *cv = smartlist_new();
  1320. ++n_versioning_clients;
  1321. smartlist_split_string(cv, v->client_versions, ",",
  1322. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1323. sort_version_list(cv, 1);
  1324. smartlist_add_all(combined_client_versions, cv);
  1325. smartlist_free(cv); /* elements get freed later. */
  1326. }
  1327. if (v->server_versions) {
  1328. smartlist_t *sv = smartlist_new();
  1329. ++n_versioning_servers;
  1330. smartlist_split_string(sv, v->server_versions, ",",
  1331. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1332. sort_version_list(sv, 1);
  1333. smartlist_add_all(combined_server_versions, sv);
  1334. smartlist_free(sv); /* elements get freed later. */
  1335. }
  1336. SMARTLIST_FOREACH(v->known_flags, const char *, cp,
  1337. smartlist_add(flags, tor_strdup(cp)));
  1338. } SMARTLIST_FOREACH_END(v);
  1339. valid_after = median_time(va_times, n_votes);
  1340. fresh_until = median_time(fu_times, n_votes);
  1341. valid_until = median_time(vu_times, n_votes);
  1342. vote_seconds = median_int(votesec_list, n_votes);
  1343. dist_seconds = median_int(distsec_list, n_votes);
  1344. tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
  1345. tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
  1346. tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
  1347. tor_assert(dist_seconds >= MIN_DIST_SECONDS);
  1348. server_versions = compute_consensus_versions_list(combined_server_versions,
  1349. n_versioning_servers);
  1350. client_versions = compute_consensus_versions_list(combined_client_versions,
  1351. n_versioning_clients);
  1352. SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
  1353. SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
  1354. smartlist_free(combined_server_versions);
  1355. smartlist_free(combined_client_versions);
  1356. smartlist_sort_strings(flags);
  1357. smartlist_uniq_strings(flags);
  1358. tor_free(va_times);
  1359. tor_free(fu_times);
  1360. tor_free(vu_times);
  1361. tor_free(votesec_list);
  1362. tor_free(distsec_list);
  1363. }
  1364. chunks = smartlist_new();
  1365. {
  1366. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  1367. vu_buf[ISO_TIME_LEN+1];
  1368. char *flaglist;
  1369. format_iso_time(va_buf, valid_after);
  1370. format_iso_time(fu_buf, fresh_until);
  1371. format_iso_time(vu_buf, valid_until);
  1372. flaglist = smartlist_join_strings(flags, " ", 0, NULL);
  1373. smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
  1374. "vote-status consensus\n",
  1375. flavor == FLAV_NS ? "" : " ",
  1376. flavor == FLAV_NS ? "" : flavor_name);
  1377. if (consensus_method >= 2) {
  1378. smartlist_add_asprintf(chunks, "consensus-method %d\n",
  1379. consensus_method);
  1380. }
  1381. smartlist_add_asprintf(chunks,
  1382. "valid-after %s\n"
  1383. "fresh-until %s\n"
  1384. "valid-until %s\n"
  1385. "voting-delay %d %d\n"
  1386. "client-versions %s\n"
  1387. "server-versions %s\n"
  1388. "known-flags %s\n",
  1389. va_buf, fu_buf, vu_buf,
  1390. vote_seconds, dist_seconds,
  1391. client_versions, server_versions, flaglist);
  1392. tor_free(flaglist);
  1393. }
  1394. if (consensus_method >= MIN_METHOD_FOR_PARAMS) {
  1395. params = dirvote_compute_params(votes, consensus_method,
  1396. total_authorities);
  1397. if (params) {
  1398. smartlist_add(chunks, tor_strdup("params "));
  1399. smartlist_add(chunks, params);
  1400. smartlist_add(chunks, tor_strdup("\n"));
  1401. }
  1402. }
  1403. /* Sort the votes. */
  1404. smartlist_sort(votes, compare_votes_by_authority_id_);
  1405. /* Add the authority sections. */
  1406. {
  1407. smartlist_t *dir_sources = smartlist_new();
  1408. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1409. dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
  1410. e->v = v;
  1411. e->digest = get_voter(v)->identity_digest;
  1412. e->is_legacy = 0;
  1413. smartlist_add(dir_sources, e);
  1414. if (consensus_method >= 3 &&
  1415. !tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
  1416. dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
  1417. e_legacy->v = v;
  1418. e_legacy->digest = get_voter(v)->legacy_id_digest;
  1419. e_legacy->is_legacy = 1;
  1420. smartlist_add(dir_sources, e_legacy);
  1421. }
  1422. } SMARTLIST_FOREACH_END(v);
  1423. smartlist_sort(dir_sources, compare_dir_src_ents_by_authority_id_);
  1424. SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
  1425. char fingerprint[HEX_DIGEST_LEN+1];
  1426. char votedigest[HEX_DIGEST_LEN+1];
  1427. networkstatus_t *v = e->v;
  1428. networkstatus_voter_info_t *voter = get_voter(v);
  1429. if (e->is_legacy)
  1430. tor_assert(consensus_method >= 2);
  1431. base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
  1432. base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
  1433. DIGEST_LEN);
  1434. smartlist_add_asprintf(chunks,
  1435. "dir-source %s%s %s %s %s %d %d\n",
  1436. voter->nickname, e->is_legacy ? "-legacy" : "",
  1437. fingerprint, voter->address, fmt_addr32(voter->addr),
  1438. voter->dir_port,
  1439. voter->or_port);
  1440. if (! e->is_legacy) {
  1441. smartlist_add_asprintf(chunks,
  1442. "contact %s\n"
  1443. "vote-digest %s\n",
  1444. voter->contact,
  1445. votedigest);
  1446. }
  1447. } SMARTLIST_FOREACH_END(e);
  1448. SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
  1449. smartlist_free(dir_sources);
  1450. }
  1451. if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW) {
  1452. char *max_unmeasured_param = NULL;
  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. strmap_t *name_to_id_map = strmap_new();
  1499. char conflict[DIGEST_LEN];
  1500. char unknown[DIGEST_LEN];
  1501. memset(conflict, 0, sizeof(conflict));
  1502. memset(unknown, 0xff, sizeof(conflict));
  1503. index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  1504. size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  1505. n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  1506. n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
  1507. flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  1508. named_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  1509. unnamed_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  1510. for (i = 0; i < smartlist_len(votes); ++i)
  1511. unnamed_flag[i] = named_flag[i] = -1;
  1512. chosen_named_idx = smartlist_string_pos(flags, "Named");
  1513. /* Build the flag index. */
  1514. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1515. flag_map[v_sl_idx] = tor_malloc_zero(
  1516. sizeof(int)*smartlist_len(v->known_flags));
  1517. SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
  1518. int p = smartlist_string_pos(flags, fl);
  1519. tor_assert(p >= 0);
  1520. flag_map[v_sl_idx][fl_sl_idx] = p;
  1521. ++n_flag_voters[p];
  1522. if (!strcmp(fl, "Named"))
  1523. named_flag[v_sl_idx] = fl_sl_idx;
  1524. if (!strcmp(fl, "Unnamed"))
  1525. unnamed_flag[v_sl_idx] = fl_sl_idx;
  1526. } SMARTLIST_FOREACH_END(fl);
  1527. n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
  1528. size[v_sl_idx] = smartlist_len(v->routerstatus_list);
  1529. } SMARTLIST_FOREACH_END(v);
  1530. /* Named and Unnamed get treated specially */
  1531. if (consensus_method >= 2) {
  1532. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1533. uint64_t nf;
  1534. if (named_flag[v_sl_idx]<0)
  1535. continue;
  1536. nf = U64_LITERAL(1) << named_flag[v_sl_idx];
  1537. SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
  1538. vote_routerstatus_t *, rs) {
  1539. if ((rs->flags & nf) != 0) {
  1540. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  1541. if (!d) {
  1542. /* We have no name officially mapped to this digest. */
  1543. strmap_set_lc(name_to_id_map, rs->status.nickname,
  1544. rs->status.identity_digest);
  1545. } else if (d != conflict &&
  1546. fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
  1547. /* Authorities disagree about this nickname. */
  1548. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  1549. } else {
  1550. /* It's already a conflict, or it's already this ID. */
  1551. }
  1552. }
  1553. } SMARTLIST_FOREACH_END(rs);
  1554. } SMARTLIST_FOREACH_END(v);
  1555. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1556. uint64_t uf;
  1557. if (unnamed_flag[v_sl_idx]<0)
  1558. continue;
  1559. uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
  1560. SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
  1561. vote_routerstatus_t *, rs) {
  1562. if ((rs->flags & uf) != 0) {
  1563. const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
  1564. if (d == conflict || d == unknown) {
  1565. /* Leave it alone; we know what it is. */
  1566. } else if (!d) {
  1567. /* We have no name officially mapped to this digest. */
  1568. strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
  1569. } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
  1570. /* Authorities disagree about this nickname. */
  1571. strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
  1572. } else {
  1573. /* It's mapped to a different name. */
  1574. }
  1575. }
  1576. } SMARTLIST_FOREACH_END(rs);
  1577. } SMARTLIST_FOREACH_END(v);
  1578. }
  1579. /* Now go through all the votes */
  1580. flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
  1581. while (1) {
  1582. vote_routerstatus_t *rs;
  1583. routerstatus_t rs_out;
  1584. const char *lowest_id = NULL;
  1585. const char *chosen_version;
  1586. const char *chosen_name = NULL;
  1587. int exitsummary_disagreement = 0;
  1588. int is_named = 0, is_unnamed = 0, is_running = 0;
  1589. int is_guard = 0, is_exit = 0, is_bad_exit = 0;
  1590. int naming_conflict = 0;
  1591. int n_listing = 0;
  1592. int i;
  1593. char microdesc_digest[DIGEST256_LEN];
  1594. tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
  1595. /* Of the next-to-be-considered digest in each voter, which is first? */
  1596. SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
  1597. if (index[v_sl_idx] < size[v_sl_idx]) {
  1598. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  1599. if (!lowest_id ||
  1600. fast_memcmp(rs->status.identity_digest,
  1601. lowest_id, DIGEST_LEN) < 0)
  1602. lowest_id = rs->status.identity_digest;
  1603. }
  1604. });
  1605. if (!lowest_id) /* we're out of routers. */
  1606. break;
  1607. memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
  1608. smartlist_clear(matching_descs);
  1609. smartlist_clear(chosen_flags);
  1610. smartlist_clear(versions);
  1611. num_bandwidths = 0;
  1612. num_mbws = 0;
  1613. /* Okay, go through all the entries for this digest. */
  1614. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  1615. if (index[v_sl_idx] >= size[v_sl_idx])
  1616. continue; /* out of entries. */
  1617. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  1618. if (fast_memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
  1619. continue; /* doesn't include this router. */
  1620. /* At this point, we know that we're looking at a routerstatus with
  1621. * identity "lowest".
  1622. */
  1623. ++index[v_sl_idx];
  1624. ++n_listing;
  1625. smartlist_add(matching_descs, rs);
  1626. if (rs->version && rs->version[0])
  1627. smartlist_add(versions, rs->version);
  1628. /* Tally up all the flags. */
  1629. for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
  1630. if (rs->flags & (U64_LITERAL(1) << i))
  1631. ++flag_counts[flag_map[v_sl_idx][i]];
  1632. }
  1633. if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
  1634. if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
  1635. log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
  1636. chosen_name, rs->status.nickname);
  1637. naming_conflict = 1;
  1638. }
  1639. chosen_name = rs->status.nickname;
  1640. }
  1641. /* count bandwidths */
  1642. if (rs->status.has_measured_bw)
  1643. measured_bws[num_mbws++] = rs->status.measured_bw;
  1644. if (rs->status.has_bandwidth)
  1645. bandwidths[num_bandwidths++] = rs->status.bandwidth;
  1646. } SMARTLIST_FOREACH_END(v);
  1647. /* We don't include this router at all unless more than half of
  1648. * the authorities we believe in list it. */
  1649. if (n_listing <= total_authorities/2)
  1650. continue;
  1651. /* Figure out the most popular opinion of what the most recent
  1652. * routerinfo and its contents are. */
  1653. memset(microdesc_digest, 0, sizeof(microdesc_digest));
  1654. rs = compute_routerstatus_consensus(matching_descs, consensus_method,
  1655. microdesc_digest, &alt_orport);
  1656. /* Copy bits of that into rs_out. */
  1657. memset(&rs_out, 0, sizeof(rs_out));
  1658. tor_assert(fast_memeq(lowest_id, rs->status.identity_digest,DIGEST_LEN));
  1659. memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
  1660. memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
  1661. DIGEST_LEN);
  1662. rs_out.addr = rs->status.addr;
  1663. rs_out.published_on = rs->status.published_on;
  1664. rs_out.dir_port = rs->status.dir_port;
  1665. rs_out.or_port = rs->status.or_port;
  1666. if (consensus_method >= MIN_METHOD_FOR_A_LINES) {
  1667. tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
  1668. rs_out.ipv6_orport = alt_orport.port;
  1669. }
  1670. rs_out.has_bandwidth = 0;
  1671. rs_out.has_exitsummary = 0;
  1672. if (chosen_name && !naming_conflict) {
  1673. strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
  1674. } else {
  1675. strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
  1676. }
  1677. if (consensus_method == 1) {
  1678. is_named = chosen_named_idx >= 0 &&
  1679. (!naming_conflict && flag_counts[chosen_named_idx]);
  1680. } else {
  1681. const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
  1682. if (!d) {
  1683. is_named = is_unnamed = 0;
  1684. } else if (fast_memeq(d, lowest_id, DIGEST_LEN)) {
  1685. is_named = 1; is_unnamed = 0;
  1686. } else {
  1687. is_named = 0; is_unnamed = 1;
  1688. }
  1689. }
  1690. /* Set the flags. */
  1691. smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
  1692. SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
  1693. if (!strcmp(fl, "Named")) {
  1694. if (is_named)
  1695. smartlist_add(chosen_flags, (char*)fl);
  1696. } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
  1697. if (is_unnamed)
  1698. smartlist_add(chosen_flags, (char*)fl);
  1699. } else {
  1700. if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
  1701. smartlist_add(chosen_flags, (char*)fl);
  1702. if (!strcmp(fl, "Exit"))
  1703. is_exit = 1;
  1704. else if (!strcmp(fl, "Guard"))
  1705. is_guard = 1;
  1706. else if (!strcmp(fl, "Running"))
  1707. is_running = 1;
  1708. else if (!strcmp(fl, "BadExit"))
  1709. is_bad_exit = 1;
  1710. }
  1711. }
  1712. } SMARTLIST_FOREACH_END(fl);
  1713. /* Starting with consensus method 4 we do not list servers
  1714. * that are not running in a consensus. See Proposal 138 */
  1715. if (consensus_method >= 4 && !is_running)
  1716. continue;
  1717. /* Pick the version. */
  1718. if (smartlist_len(versions)) {
  1719. sort_version_list(versions, 0);
  1720. chosen_version = get_most_frequent_member(versions);
  1721. } else {
  1722. chosen_version = NULL;
  1723. }
  1724. /* Pick a bandwidth */
  1725. if (consensus_method >= 6 && num_mbws > 2) {
  1726. rs_out.has_bandwidth = 1;
  1727. rs_out.bandwidth = median_uint32(measured_bws, num_mbws);
  1728. } else if (consensus_method >= 5 && num_bandwidths > 0) {
  1729. rs_out.has_bandwidth = 1;
  1730. rs_out.bandwidth = median_uint32(bandwidths, num_bandwidths);
  1731. if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW) {
  1732. /* Cap non-measured bandwidths to 20k. */
  1733. if (rs_out.bandwidth > max_unmeasured_bw)
  1734. rs_out.bandwidth = max_unmeasured_bw;
  1735. }
  1736. }
  1737. /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
  1738. if (consensus_method >= 11) {
  1739. is_exit = is_exit && !is_bad_exit;
  1740. }
  1741. if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
  1742. if (rs_out.has_bandwidth) {
  1743. T += rs_out.bandwidth;
  1744. if (is_exit && is_guard)
  1745. D += rs_out.bandwidth;
  1746. else if (is_exit)
  1747. E += rs_out.bandwidth;
  1748. else if (is_guard)
  1749. G += rs_out.bandwidth;
  1750. else
  1751. M += rs_out.bandwidth;
  1752. } else {
  1753. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  1754. rs_out.nickname);
  1755. }
  1756. }
  1757. /* Ok, we already picked a descriptor digest we want to list
  1758. * previously. Now we want to use the exit policy summary from
  1759. * that descriptor. If everybody plays nice all the voters who
  1760. * listed that descriptor will have the same summary. If not then
  1761. * something is fishy and we'll use the most common one (breaking
  1762. * ties in favor of lexicographically larger one (only because it
  1763. * lets me reuse more existing code)).
  1764. *
  1765. * The other case that can happen is that no authority that voted
  1766. * for that descriptor has an exit policy summary. That's
  1767. * probably quite unlikely but can happen. In that case we use
  1768. * the policy that was most often listed in votes, again breaking
  1769. * ties like in the previous case.
  1770. */
  1771. if (consensus_method >= 5) {
  1772. /* Okay, go through all the votes for this router. We prepared
  1773. * that list previously */
  1774. const char *chosen_exitsummary = NULL;
  1775. smartlist_clear(exitsummaries);
  1776. SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
  1777. /* Check if the vote where this status comes from had the
  1778. * proper descriptor */
  1779. tor_assert(fast_memeq(rs_out.identity_digest,
  1780. vsr->status.identity_digest,
  1781. DIGEST_LEN));
  1782. if (vsr->status.has_exitsummary &&
  1783. fast_memeq(rs_out.descriptor_digest,
  1784. vsr->status.descriptor_digest,
  1785. DIGEST_LEN)) {
  1786. tor_assert(vsr->status.exitsummary);
  1787. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1788. if (!chosen_exitsummary) {
  1789. chosen_exitsummary = vsr->status.exitsummary;
  1790. } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
  1791. /* Great. There's disagreement among the voters. That
  1792. * really shouldn't be */
  1793. exitsummary_disagreement = 1;
  1794. }
  1795. }
  1796. } SMARTLIST_FOREACH_END(vsr);
  1797. if (exitsummary_disagreement) {
  1798. char id[HEX_DIGEST_LEN+1];
  1799. char dd[HEX_DIGEST_LEN+1];
  1800. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1801. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1802. log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
  1803. " for router %s with descriptor %s. This really shouldn't"
  1804. " have happened.", id, dd);
  1805. smartlist_sort_strings(exitsummaries);
  1806. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1807. } else if (!chosen_exitsummary) {
  1808. char id[HEX_DIGEST_LEN+1];
  1809. char dd[HEX_DIGEST_LEN+1];
  1810. base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
  1811. base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
  1812. log_warn(LD_DIR, "Not one of the voters that made us select"
  1813. "descriptor %s for router %s had an exit policy"
  1814. "summary", dd, id);
  1815. /* Ok, none of those voting for the digest we chose had an
  1816. * exit policy for us. Well, that kinda sucks.
  1817. */
  1818. smartlist_clear(exitsummaries);
  1819. SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
  1820. if (vsr->status.has_exitsummary)
  1821. smartlist_add(exitsummaries, vsr->status.exitsummary);
  1822. });
  1823. smartlist_sort_strings(exitsummaries);
  1824. chosen_exitsummary = get_most_frequent_member(exitsummaries);
  1825. if (!chosen_exitsummary)
  1826. log_warn(LD_DIR, "Wow, not one of the voters had an exit "
  1827. "policy summary for %s. Wow.", id);
  1828. }
  1829. if (chosen_exitsummary) {
  1830. rs_out.has_exitsummary = 1;
  1831. /* yea, discards the const */
  1832. rs_out.exitsummary = (char *)chosen_exitsummary;
  1833. }
  1834. }
  1835. if (flavor == FLAV_MICRODESC &&
  1836. consensus_method >= MIN_METHOD_FOR_MANDATORY_MICRODESC &&
  1837. tor_digest256_is_zero(microdesc_digest)) {
  1838. /* With no microdescriptor digest, we omit the entry entirely. */
  1839. continue;
  1840. }
  1841. {
  1842. char buf[4096];
  1843. /* Okay!! Now we can write the descriptor... */
  1844. /* First line goes into "buf". */
  1845. routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL,
  1846. rs_format);
  1847. smartlist_add(chunks, tor_strdup(buf));
  1848. }
  1849. /* Now an m line, if applicable. */
  1850. if (flavor == FLAV_MICRODESC &&
  1851. !tor_digest256_is_zero(microdesc_digest)) {
  1852. char m[BASE64_DIGEST256_LEN+1];
  1853. digest256_to_base64(m, microdesc_digest);
  1854. smartlist_add_asprintf(chunks, "m %s\n", m);
  1855. }
  1856. /* Next line is all flags. The "\n" is missing. */
  1857. smartlist_add(chunks,
  1858. smartlist_join_strings(chosen_flags, " ", 0, NULL));
  1859. /* Now the version line. */
  1860. if (chosen_version) {
  1861. smartlist_add(chunks, tor_strdup("\nv "));
  1862. smartlist_add(chunks, tor_strdup(chosen_version));
  1863. }
  1864. smartlist_add(chunks, tor_strdup("\n"));
  1865. /* Now the weight line. */
  1866. if (rs_out.has_bandwidth) {
  1867. smartlist_add_asprintf(chunks, "w Bandwidth=%d\n", rs_out.bandwidth);
  1868. }
  1869. /* Now the exitpolicy summary line. */
  1870. if (rs_out.has_exitsummary && flavor == FLAV_NS) {
  1871. smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
  1872. }
  1873. /* And the loop is over and we move on to the next router */
  1874. }
  1875. tor_free(index);
  1876. tor_free(size);
  1877. tor_free(n_voter_flags);
  1878. tor_free(n_flag_voters);
  1879. for (i = 0; i < smartlist_len(votes); ++i)
  1880. tor_free(flag_map[i]);
  1881. tor_free(flag_map);
  1882. tor_free(flag_counts);
  1883. tor_free(named_flag);
  1884. tor_free(unnamed_flag);
  1885. strmap_free(name_to_id_map, NULL);
  1886. smartlist_free(matching_descs);
  1887. smartlist_free(chosen_flags);
  1888. smartlist_free(versions);
  1889. smartlist_free(exitsummaries);
  1890. tor_free(bandwidths);
  1891. tor_free(measured_bws);
  1892. }
  1893. if (consensus_method >= MIN_METHOD_FOR_FOOTER) {
  1894. /* Starting with consensus method 9, we clearly mark the directory
  1895. * footer region */
  1896. smartlist_add(chunks, tor_strdup("directory-footer\n"));
  1897. }
  1898. if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
  1899. int64_t weight_scale = BW_WEIGHT_SCALE;
  1900. char *bw_weight_param = NULL;
  1901. // Parse params, extract BW_WEIGHT_SCALE if present
  1902. // DO NOT use consensus_param_bw_weight_scale() in this code!
  1903. // The consensus is not formed yet!
  1904. if (params) {
  1905. if (strcmpstart(params, "bwweightscale=") == 0)
  1906. bw_weight_param = params;
  1907. else
  1908. bw_weight_param = strstr(params, " bwweightscale=");
  1909. }
  1910. if (bw_weight_param) {
  1911. int ok=0;
  1912. char *eq = strchr(bw_weight_param, '=');
  1913. if (eq) {
  1914. weight_scale = tor_parse_long(eq+1, 10, 1, INT32_MAX, &ok,
  1915. NULL);
  1916. if (!ok) {
  1917. log_warn(LD_DIR, "Bad element '%s' in bw weight param",
  1918. escaped(bw_weight_param));
  1919. weight_scale = BW_WEIGHT_SCALE;
  1920. }
  1921. } else {
  1922. log_warn(LD_DIR, "Bad element '%s' in bw weight param",
  1923. escaped(bw_weight_param));
  1924. weight_scale = BW_WEIGHT_SCALE;
  1925. }
  1926. }
  1927. if (consensus_method < 10) {
  1928. networkstatus_compute_bw_weights_v9(chunks, G, M, E, D, T, weight_scale);
  1929. added_weights = 1;
  1930. } else {
  1931. added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
  1932. T, weight_scale);
  1933. }
  1934. }
  1935. /* Add a signature. */
  1936. {
  1937. char digest[DIGEST256_LEN];
  1938. char fingerprint[HEX_DIGEST_LEN+1];
  1939. char signing_key_fingerprint[HEX_DIGEST_LEN+1];
  1940. digest_algorithm_t digest_alg =
  1941. flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
  1942. size_t digest_len =
  1943. flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
  1944. const char *algname = crypto_digest_algorithm_get_name(digest_alg);
  1945. char sigbuf[4096];
  1946. smartlist_add(chunks, tor_strdup("directory-signature "));
  1947. /* Compute the hash of the chunks. */
  1948. hash_list_members(digest, digest_len, chunks, digest_alg);
  1949. /* Get the fingerprints */
  1950. crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
  1951. crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
  1952. /* add the junk that will go at the end of the line. */
  1953. if (flavor == FLAV_NS) {
  1954. smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
  1955. signing_key_fingerprint);
  1956. } else {
  1957. smartlist_add_asprintf(chunks, "%s %s %s\n",
  1958. algname, fingerprint,
  1959. signing_key_fingerprint);
  1960. }
  1961. /* And the signature. */
  1962. sigbuf[0] = '\0';
  1963. if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
  1964. digest, digest_len,
  1965. signing_key)) {
  1966. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1967. return NULL; /* This leaks, but it should never happen. */
  1968. }
  1969. smartlist_add(chunks, tor_strdup(sigbuf));
  1970. if (legacy_id_key_digest && legacy_signing_key && consensus_method >= 3) {
  1971. smartlist_add(chunks, tor_strdup("directory-signature "));
  1972. base16_encode(fingerprint, sizeof(fingerprint),
  1973. legacy_id_key_digest, DIGEST_LEN);
  1974. crypto_pk_get_fingerprint(legacy_signing_key,
  1975. signing_key_fingerprint, 0);
  1976. if (flavor == FLAV_NS) {
  1977. smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
  1978. signing_key_fingerprint);
  1979. } else {
  1980. smartlist_add_asprintf(chunks, "%s %s %s\n",
  1981. algname, fingerprint,
  1982. signing_key_fingerprint);
  1983. }
  1984. sigbuf[0] = '\0';
  1985. if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
  1986. digest, digest_len,
  1987. legacy_signing_key)) {
  1988. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  1989. return NULL; /* This leaks, but it should never happen. */
  1990. }
  1991. smartlist_add(chunks, tor_strdup(sigbuf));
  1992. }
  1993. }
  1994. result = smartlist_join_strings(chunks, "", 0, NULL);
  1995. tor_free(client_versions);
  1996. tor_free(server_versions);
  1997. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  1998. smartlist_free(flags);
  1999. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2000. smartlist_free(chunks);
  2001. {
  2002. networkstatus_t *c;
  2003. if (!(c = networkstatus_parse_vote_from_string(result, NULL,
  2004. NS_TYPE_CONSENSUS))) {
  2005. log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
  2006. "parse.");
  2007. tor_free(result);
  2008. return NULL;
  2009. }
  2010. // Verify balancing parameters
  2011. if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS && added_weights) {
  2012. networkstatus_verify_bw_weights(c);
  2013. }
  2014. networkstatus_vote_free(c);
  2015. }
  2016. return result;
  2017. }
  2018. /** Given a consensus vote <b>target</b> and a set of detached signatures in
  2019. * <b>sigs</b> that correspond to the same consensus, check whether there are
  2020. * any new signatures in <b>src_voter_list</b> that should be added to
  2021. * <b>target</b>. (A signature should be added if we have no signature for that
  2022. * voter in <b>target</b> yet, or if we have no verifiable signature and the
  2023. * new signature is verifiable.) Return the number of signatures added or
  2024. * changed, or -1 if the document signed by <b>sigs</b> isn't the same
  2025. * document as <b>target</b>. */
  2026. int
  2027. networkstatus_add_detached_signatures(networkstatus_t *target,
  2028. ns_detached_signatures_t *sigs,
  2029. const char *source,
  2030. int severity,
  2031. const char **msg_out)
  2032. {
  2033. int r = 0;
  2034. const char *flavor;
  2035. smartlist_t *siglist;
  2036. tor_assert(sigs);
  2037. tor_assert(target);
  2038. tor_assert(target->type == NS_TYPE_CONSENSUS);
  2039. flavor = networkstatus_get_flavor_name(target->flavor);
  2040. /* Do the times seem right? */
  2041. if (target->valid_after != sigs->valid_after) {
  2042. *msg_out = "Valid-After times do not match "
  2043. "when adding detached signatures to consensus";
  2044. return -1;
  2045. }
  2046. if (target->fresh_until != sigs->fresh_until) {
  2047. *msg_out = "Fresh-until times do not match "
  2048. "when adding detached signatures to consensus";
  2049. return -1;
  2050. }
  2051. if (target->valid_until != sigs->valid_until) {
  2052. *msg_out = "Valid-until times do not match "
  2053. "when adding detached signatures to consensus";
  2054. return -1;
  2055. }
  2056. siglist = strmap_get(sigs->signatures, flavor);
  2057. if (!siglist) {
  2058. *msg_out = "No signatures for given consensus flavor";
  2059. return -1;
  2060. }
  2061. /** Make sure all the digests we know match, and at least one matches. */
  2062. {
  2063. digests_t *digests = strmap_get(sigs->digests, flavor);
  2064. int n_matches = 0;
  2065. int alg;
  2066. if (!digests) {
  2067. *msg_out = "No digests for given consensus flavor";
  2068. return -1;
  2069. }
  2070. for (alg = DIGEST_SHA1; alg < N_DIGEST_ALGORITHMS; ++alg) {
  2071. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  2072. if (fast_memeq(target->digests.d[alg], digests->d[alg],
  2073. DIGEST256_LEN)) {
  2074. ++n_matches;
  2075. } else {
  2076. *msg_out = "Mismatched digest.";
  2077. return -1;
  2078. }
  2079. }
  2080. }
  2081. if (!n_matches) {
  2082. *msg_out = "No regognized digests for given consensus flavor";
  2083. }
  2084. }
  2085. /* For each voter in src... */
  2086. SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
  2087. char voter_identity[HEX_DIGEST_LEN+1];
  2088. networkstatus_voter_info_t *target_voter =
  2089. networkstatus_get_voter_by_id(target, sig->identity_digest);
  2090. authority_cert_t *cert = NULL;
  2091. const char *algorithm;
  2092. document_signature_t *old_sig = NULL;
  2093. algorithm = crypto_digest_algorithm_get_name(sig->alg);
  2094. base16_encode(voter_identity, sizeof(voter_identity),
  2095. sig->identity_digest, DIGEST_LEN);
  2096. log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
  2097. algorithm);
  2098. /* If the target doesn't know about this voter, then forget it. */
  2099. if (!target_voter) {
  2100. log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
  2101. continue;
  2102. }
  2103. old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
  2104. /* If the target already has a good signature from this voter, then skip
  2105. * this one. */
  2106. if (old_sig && old_sig->good_signature) {
  2107. log_info(LD_DIR, "We already have a good signature from %s using %s",
  2108. voter_identity, algorithm);
  2109. continue;
  2110. }
  2111. /* Try checking the signature if we haven't already. */
  2112. if (!sig->good_signature && !sig->bad_signature) {
  2113. cert = authority_cert_get_by_digests(sig->identity_digest,
  2114. sig->signing_key_digest);
  2115. if (cert)
  2116. networkstatus_check_document_signature(target, sig, cert);
  2117. }
  2118. /* If this signature is good, or we don't have any signature yet,
  2119. * then maybe add it. */
  2120. if (sig->good_signature || !old_sig || old_sig->bad_signature) {
  2121. log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
  2122. algorithm);
  2123. tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
  2124. target_voter->nickname, source);
  2125. ++r;
  2126. if (old_sig) {
  2127. smartlist_remove(target_voter->sigs, old_sig);
  2128. document_signature_free(old_sig);
  2129. }
  2130. smartlist_add(target_voter->sigs, document_signature_dup(sig));
  2131. } else {
  2132. log_info(LD_DIR, "Not adding signature from %s", voter_identity);
  2133. }
  2134. } SMARTLIST_FOREACH_END(sig);
  2135. return r;
  2136. }
  2137. /** Return a newly allocated string containing all the signatures on
  2138. * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
  2139. * then the signatures will be put in a detached signatures document, so
  2140. * prefix any non-NS-flavored signatures with "additional-signature" rather
  2141. * than "directory-signature". */
  2142. static char *
  2143. networkstatus_format_signatures(networkstatus_t *consensus,
  2144. int for_detached_signatures)
  2145. {
  2146. smartlist_t *elements;
  2147. char buf[4096];
  2148. char *result = NULL;
  2149. int n_sigs = 0;
  2150. const consensus_flavor_t flavor = consensus->flavor;
  2151. const char *flavor_name = networkstatus_get_flavor_name(flavor);
  2152. const char *keyword;
  2153. if (for_detached_signatures && flavor != FLAV_NS)
  2154. keyword = "additional-signature";
  2155. else
  2156. keyword = "directory-signature";
  2157. elements = smartlist_new();
  2158. SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
  2159. SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
  2160. char sk[HEX_DIGEST_LEN+1];
  2161. char id[HEX_DIGEST_LEN+1];
  2162. if (!sig->signature || sig->bad_signature)
  2163. continue;
  2164. ++n_sigs;
  2165. base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
  2166. base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
  2167. if (flavor == FLAV_NS) {
  2168. smartlist_add_asprintf(elements,
  2169. "%s %s %s\n-----BEGIN SIGNATURE-----\n",
  2170. keyword, id, sk);
  2171. } else {
  2172. const char *digest_name =
  2173. crypto_digest_algorithm_get_name(sig->alg);
  2174. smartlist_add_asprintf(elements,
  2175. "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
  2176. keyword,
  2177. for_detached_signatures ? " " : "",
  2178. for_detached_signatures ? flavor_name : "",
  2179. digest_name, id, sk);
  2180. }
  2181. base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len);
  2182. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  2183. smartlist_add(elements, tor_strdup(buf));
  2184. } SMARTLIST_FOREACH_END(sig);
  2185. } SMARTLIST_FOREACH_END(v);
  2186. result = smartlist_join_strings(elements, "", 0, NULL);
  2187. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2188. smartlist_free(elements);
  2189. if (!n_sigs)
  2190. tor_free(result);
  2191. return result;
  2192. }
  2193. /** Return a newly allocated string holding the detached-signatures document
  2194. * corresponding to the signatures on <b>consensuses</b>, which must contain
  2195. * exactly one FLAV_NS consensus, and no more than one consensus for each
  2196. * other flavor. */
  2197. char *
  2198. networkstatus_get_detached_signatures(smartlist_t *consensuses)
  2199. {
  2200. smartlist_t *elements;
  2201. char *result = NULL, *sigs = NULL;
  2202. networkstatus_t *consensus_ns = NULL;
  2203. tor_assert(consensuses);
  2204. SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
  2205. tor_assert(ns);
  2206. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2207. if (ns && ns->flavor == FLAV_NS)
  2208. consensus_ns = ns;
  2209. });
  2210. if (!consensus_ns) {
  2211. log_warn(LD_BUG, "No NS consensus given.");
  2212. return NULL;
  2213. }
  2214. elements = smartlist_new();
  2215. {
  2216. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  2217. vu_buf[ISO_TIME_LEN+1];
  2218. char d[HEX_DIGEST_LEN+1];
  2219. base16_encode(d, sizeof(d),
  2220. consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
  2221. format_iso_time(va_buf, consensus_ns->valid_after);
  2222. format_iso_time(fu_buf, consensus_ns->fresh_until);
  2223. format_iso_time(vu_buf, consensus_ns->valid_until);
  2224. smartlist_add_asprintf(elements,
  2225. "consensus-digest %s\n"
  2226. "valid-after %s\n"
  2227. "fresh-until %s\n"
  2228. "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
  2229. }
  2230. /* Get all the digests for the non-FLAV_NS consensuses */
  2231. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  2232. const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
  2233. int alg;
  2234. if (ns->flavor == FLAV_NS)
  2235. continue;
  2236. /* start with SHA256; we don't include SHA1 for anything but the basic
  2237. * consensus. */
  2238. for (alg = DIGEST_SHA256; alg < N_DIGEST_ALGORITHMS; ++alg) {
  2239. char d[HEX_DIGEST256_LEN+1];
  2240. const char *alg_name =
  2241. crypto_digest_algorithm_get_name(alg);
  2242. if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
  2243. continue;
  2244. base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
  2245. smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
  2246. flavor_name, alg_name, d);
  2247. }
  2248. } SMARTLIST_FOREACH_END(ns);
  2249. /* Now get all the sigs for non-FLAV_NS consensuses */
  2250. SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
  2251. char *sigs;
  2252. if (ns->flavor == FLAV_NS)
  2253. continue;
  2254. sigs = networkstatus_format_signatures(ns, 1);
  2255. if (!sigs) {
  2256. log_warn(LD_DIR, "Couldn't format signatures");
  2257. goto err;
  2258. }
  2259. smartlist_add(elements, sigs);
  2260. } SMARTLIST_FOREACH_END(ns);
  2261. /* Now add the FLAV_NS consensus signatrures. */
  2262. sigs = networkstatus_format_signatures(consensus_ns, 1);
  2263. if (!sigs)
  2264. goto err;
  2265. smartlist_add(elements, sigs);
  2266. result = smartlist_join_strings(elements, "", 0, NULL);
  2267. err:
  2268. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2269. smartlist_free(elements);
  2270. return result;
  2271. }
  2272. /** Return a newly allocated string holding a detached-signatures document for
  2273. * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
  2274. * <b>pending</b>. */
  2275. static char *
  2276. get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
  2277. int n_flavors)
  2278. {
  2279. int flav;
  2280. char *signatures;
  2281. smartlist_t *c = smartlist_new();
  2282. for (flav = 0; flav < n_flavors; ++flav) {
  2283. if (pending[flav].consensus)
  2284. smartlist_add(c, pending[flav].consensus);
  2285. }
  2286. signatures = networkstatus_get_detached_signatures(c);
  2287. smartlist_free(c);
  2288. return signatures;
  2289. }
  2290. /** Release all storage held in <b>s</b>. */
  2291. void
  2292. ns_detached_signatures_free(ns_detached_signatures_t *s)
  2293. {
  2294. if (!s)
  2295. return;
  2296. if (s->signatures) {
  2297. STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
  2298. SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
  2299. document_signature_free(sig));
  2300. smartlist_free(sigs);
  2301. } STRMAP_FOREACH_END;
  2302. strmap_free(s->signatures, NULL);
  2303. strmap_free(s->digests, tor_free_);
  2304. }
  2305. tor_free(s);
  2306. }
  2307. /* =====
  2308. * Certificate functions
  2309. * ===== */
  2310. /** Allocate and return a new authority_cert_t with the same contents as
  2311. * <b>cert</b>. */
  2312. authority_cert_t *
  2313. authority_cert_dup(authority_cert_t *cert)
  2314. {
  2315. authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
  2316. tor_assert(cert);
  2317. memcpy(out, cert, sizeof(authority_cert_t));
  2318. /* Now copy pointed-to things. */
  2319. out->cache_info.signed_descriptor_body =
  2320. tor_strndup(cert->cache_info.signed_descriptor_body,
  2321. cert->cache_info.signed_descriptor_len);
  2322. out->cache_info.saved_location = SAVED_NOWHERE;
  2323. out->identity_key = crypto_pk_dup_key(cert->identity_key);
  2324. out->signing_key = crypto_pk_dup_key(cert->signing_key);
  2325. return out;
  2326. }
  2327. /* =====
  2328. * Vote scheduling
  2329. * ===== */
  2330. /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
  2331. * Note that these aren't the intervals we'll use to vote; they're the ones
  2332. * that we'll vote to use. */
  2333. void
  2334. dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
  2335. {
  2336. const or_options_t *options = get_options();
  2337. tor_assert(timing_out);
  2338. timing_out->vote_interval = options->V3AuthVotingInterval;
  2339. timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
  2340. timing_out->vote_delay = options->V3AuthVoteDelay;
  2341. timing_out->dist_delay = options->V3AuthDistDelay;
  2342. }
  2343. /** Return the start of the next interval of size <b>interval</b> (in seconds)
  2344. * after <b>now</b>. Midnight always starts a fresh interval, and if the last
  2345. * interval of a day would be truncated to less than half its size, it is
  2346. * rolled into the previous interval. */
  2347. time_t
  2348. dirvote_get_start_of_next_interval(time_t now, int interval)
  2349. {
  2350. struct tm tm;
  2351. time_t midnight_today=0;
  2352. time_t midnight_tomorrow;
  2353. time_t next;
  2354. tor_gmtime_r(&now, &tm);
  2355. tm.tm_hour = 0;
  2356. tm.tm_min = 0;
  2357. tm.tm_sec = 0;
  2358. if (tor_timegm(&tm, &midnight_today) < 0) {
  2359. log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
  2360. }
  2361. midnight_tomorrow = midnight_today + (24*60*60);
  2362. next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
  2363. /* Intervals never cross midnight. */
  2364. if (next > midnight_tomorrow)
  2365. next = midnight_tomorrow;
  2366. /* If the interval would only last half as long as it's supposed to, then
  2367. * skip over to the next day. */
  2368. if (next + interval/2 > midnight_tomorrow)
  2369. next = midnight_tomorrow;
  2370. return next;
  2371. }
  2372. /** Scheduling information for a voting interval. */
  2373. static struct {
  2374. /** When do we generate and distribute our vote for this interval? */
  2375. time_t voting_starts;
  2376. /** When do we send an HTTP request for any votes that we haven't
  2377. * been posted yet?*/
  2378. time_t fetch_missing_votes;
  2379. /** When do we give up on getting more votes and generate a consensus? */
  2380. time_t voting_ends;
  2381. /** When do we send an HTTP request for any signatures we're expecting to
  2382. * see on the consensus? */
  2383. time_t fetch_missing_signatures;
  2384. /** When do we publish the consensus? */
  2385. time_t interval_starts;
  2386. /* True iff we have generated and distributed our vote. */
  2387. int have_voted;
  2388. /* True iff we've requested missing votes. */
  2389. int have_fetched_missing_votes;
  2390. /* True iff we have built a consensus and sent the signatures around. */
  2391. int have_built_consensus;
  2392. /* True iff we've fetched missing signatures. */
  2393. int have_fetched_missing_signatures;
  2394. /* True iff we have published our consensus. */
  2395. int have_published_consensus;
  2396. } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
  2397. /** Set voting_schedule to hold the timing for the next vote we should be
  2398. * doing. */
  2399. void
  2400. dirvote_recalculate_timing(const or_options_t *options, time_t now)
  2401. {
  2402. int interval, vote_delay, dist_delay;
  2403. time_t start;
  2404. time_t end;
  2405. networkstatus_t *consensus;
  2406. if (!authdir_mode_v3(options))
  2407. return;
  2408. consensus = networkstatus_get_live_consensus(now);
  2409. memset(&voting_schedule, 0, sizeof(voting_schedule));
  2410. if (consensus) {
  2411. interval = (int)( consensus->fresh_until - consensus->valid_after );
  2412. vote_delay = consensus->vote_seconds;
  2413. dist_delay = consensus->dist_seconds;
  2414. } else {
  2415. interval = options->TestingV3AuthInitialVotingInterval;
  2416. vote_delay = options->TestingV3AuthInitialVoteDelay;
  2417. dist_delay = options->TestingV3AuthInitialDistDelay;
  2418. }
  2419. tor_assert(interval > 0);
  2420. if (vote_delay + dist_delay > interval/2)
  2421. vote_delay = dist_delay = interval / 4;
  2422. start = voting_schedule.interval_starts =
  2423. dirvote_get_start_of_next_interval(now,interval);
  2424. end = dirvote_get_start_of_next_interval(start+1, interval);
  2425. tor_assert(end > start);
  2426. voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
  2427. voting_schedule.voting_ends = start - dist_delay;
  2428. voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
  2429. voting_schedule.voting_starts = start - dist_delay - vote_delay;
  2430. {
  2431. char tbuf[ISO_TIME_LEN+1];
  2432. format_iso_time(tbuf, voting_schedule.interval_starts);
  2433. log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
  2434. "consensus_set=%d, interval=%d",
  2435. tbuf, consensus?1:0, interval);
  2436. }
  2437. }
  2438. /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
  2439. void
  2440. dirvote_act(const or_options_t *options, time_t now)
  2441. {
  2442. if (!authdir_mode_v3(options))
  2443. return;
  2444. if (!voting_schedule.voting_starts) {
  2445. char *keys = list_v3_auth_ids();
  2446. authority_cert_t *c = get_my_v3_authority_cert();
  2447. log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
  2448. "Mine is %s.",
  2449. keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
  2450. tor_free(keys);
  2451. dirvote_recalculate_timing(options, now);
  2452. }
  2453. if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
  2454. log_notice(LD_DIR, "Time to vote.");
  2455. dirvote_perform_vote();
  2456. voting_schedule.have_voted = 1;
  2457. }
  2458. if (voting_schedule.fetch_missing_votes < now &&
  2459. !voting_schedule.have_fetched_missing_votes) {
  2460. log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
  2461. dirvote_fetch_missing_votes();
  2462. voting_schedule.have_fetched_missing_votes = 1;
  2463. }
  2464. if (voting_schedule.voting_ends < now &&
  2465. !voting_schedule.have_built_consensus) {
  2466. log_notice(LD_DIR, "Time to compute a consensus.");
  2467. dirvote_compute_consensuses();
  2468. /* XXXX We will want to try again later if we haven't got enough
  2469. * votes yet. Implement this if it turns out to ever happen. */
  2470. voting_schedule.have_built_consensus = 1;
  2471. }
  2472. if (voting_schedule.fetch_missing_signatures < now &&
  2473. !voting_schedule.have_fetched_missing_signatures) {
  2474. log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
  2475. dirvote_fetch_missing_signatures();
  2476. voting_schedule.have_fetched_missing_signatures = 1;
  2477. }
  2478. if (voting_schedule.interval_starts < now &&
  2479. !voting_schedule.have_published_consensus) {
  2480. log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
  2481. dirvote_publish_consensus();
  2482. dirvote_clear_votes(0);
  2483. voting_schedule.have_published_consensus = 1;
  2484. /* XXXX We will want to try again later if we haven't got enough
  2485. * signatures yet. Implement this if it turns out to ever happen. */
  2486. dirvote_recalculate_timing(options, now);
  2487. }
  2488. }
  2489. /** A vote networkstatus_t and its unparsed body: held around so we can
  2490. * use it to generate a consensus (at voting_ends) and so we can serve it to
  2491. * other authorities that might want it. */
  2492. typedef struct pending_vote_t {
  2493. cached_dir_t *vote_body;
  2494. networkstatus_t *vote;
  2495. } pending_vote_t;
  2496. /** List of pending_vote_t for the current vote. Before we've used them to
  2497. * build a consensus, the votes go here. */
  2498. static smartlist_t *pending_vote_list = NULL;
  2499. /** List of pending_vote_t for the previous vote. After we've used them to
  2500. * build a consensus, the votes go here for the next period. */
  2501. static smartlist_t *previous_vote_list = NULL;
  2502. /* DOCDOC pending_consensuses */
  2503. static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
  2504. /** The detached signatures for the consensus that we're currently
  2505. * building. */
  2506. static char *pending_consensus_signatures = NULL;
  2507. /** List of ns_detached_signatures_t: hold signatures that get posted to us
  2508. * before we have generated the consensus on our own. */
  2509. static smartlist_t *pending_consensus_signature_list = NULL;
  2510. /** Generate a networkstatus vote and post it to all the v3 authorities.
  2511. * (V3 Authority only) */
  2512. static int
  2513. dirvote_perform_vote(void)
  2514. {
  2515. crypto_pk_t *key = get_my_v3_authority_signing_key();
  2516. authority_cert_t *cert = get_my_v3_authority_cert();
  2517. networkstatus_t *ns;
  2518. char *contents;
  2519. pending_vote_t *pending_vote;
  2520. time_t now = time(NULL);
  2521. int status;
  2522. const char *msg = "";
  2523. if (!cert || !key) {
  2524. log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
  2525. return -1;
  2526. } else if (cert->expires < now) {
  2527. log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
  2528. return -1;
  2529. }
  2530. if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
  2531. return -1;
  2532. contents = format_networkstatus_vote(key, ns);
  2533. networkstatus_vote_free(ns);
  2534. if (!contents)
  2535. return -1;
  2536. pending_vote = dirvote_add_vote(contents, &msg, &status);
  2537. tor_free(contents);
  2538. if (!pending_vote) {
  2539. log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
  2540. msg);
  2541. return -1;
  2542. }
  2543. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
  2544. ROUTER_PURPOSE_GENERAL,
  2545. V3_DIRINFO,
  2546. pending_vote->vote_body->dir,
  2547. pending_vote->vote_body->dir_len, 0);
  2548. log_notice(LD_DIR, "Vote posted.");
  2549. return 0;
  2550. }
  2551. /** Send an HTTP request to every other v3 authority, for the votes of every
  2552. * authority for which we haven't received a vote yet in this period. (V3
  2553. * authority only) */
  2554. static void
  2555. dirvote_fetch_missing_votes(void)
  2556. {
  2557. smartlist_t *missing_fps = smartlist_new();
  2558. char *resource;
  2559. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  2560. dir_server_t *, ds) {
  2561. if (!(ds->type & V3_DIRINFO))
  2562. continue;
  2563. if (!dirvote_get_vote(ds->v3_identity_digest,
  2564. DGV_BY_ID|DGV_INCLUDE_PENDING)) {
  2565. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  2566. base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
  2567. DIGEST_LEN);
  2568. smartlist_add(missing_fps, cp);
  2569. }
  2570. } SMARTLIST_FOREACH_END(ds);
  2571. if (!smartlist_len(missing_fps)) {
  2572. smartlist_free(missing_fps);
  2573. return;
  2574. }
  2575. {
  2576. char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
  2577. log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
  2578. "Asking every other authority for a copy.",
  2579. smartlist_len(missing_fps), tmp);
  2580. tor_free(tmp);
  2581. }
  2582. resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
  2583. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
  2584. 0, resource);
  2585. tor_free(resource);
  2586. SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
  2587. smartlist_free(missing_fps);
  2588. }
  2589. /** Send a request to every other authority for its detached signatures,
  2590. * unless we have signatures from all other v3 authorities already. */
  2591. static void
  2592. dirvote_fetch_missing_signatures(void)
  2593. {
  2594. int need_any = 0;
  2595. int i;
  2596. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  2597. networkstatus_t *consensus = pending_consensuses[i].consensus;
  2598. if (!consensus ||
  2599. networkstatus_check_consensus_signature(consensus, -1) == 1) {
  2600. /* We have no consensus, or we have one that's signed by everybody. */
  2601. continue;
  2602. }
  2603. need_any = 1;
  2604. }
  2605. if (!need_any)
  2606. return;
  2607. directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
  2608. 0, NULL);
  2609. }
  2610. /** Release all storage held by pending consensuses (those waiting for
  2611. * signatures). */
  2612. static void
  2613. dirvote_clear_pending_consensuses(void)
  2614. {
  2615. int i;
  2616. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  2617. pending_consensus_t *pc = &pending_consensuses[i];
  2618. tor_free(pc->body);
  2619. networkstatus_vote_free(pc->consensus);
  2620. pc->consensus = NULL;
  2621. }
  2622. }
  2623. /** Drop all currently pending votes, consensus, and detached signatures. */
  2624. static void
  2625. dirvote_clear_votes(int all_votes)
  2626. {
  2627. if (!previous_vote_list)
  2628. previous_vote_list = smartlist_new();
  2629. if (!pending_vote_list)
  2630. pending_vote_list = smartlist_new();
  2631. /* All "previous" votes are now junk. */
  2632. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
  2633. cached_dir_decref(v->vote_body);
  2634. v->vote_body = NULL;
  2635. networkstatus_vote_free(v->vote);
  2636. tor_free(v);
  2637. });
  2638. smartlist_clear(previous_vote_list);
  2639. if (all_votes) {
  2640. /* If we're dumping all the votes, we delete the pending ones. */
  2641. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  2642. cached_dir_decref(v->vote_body);
  2643. v->vote_body = NULL;
  2644. networkstatus_vote_free(v->vote);
  2645. tor_free(v);
  2646. });
  2647. } else {
  2648. /* Otherwise, we move them into "previous". */
  2649. smartlist_add_all(previous_vote_list, pending_vote_list);
  2650. }
  2651. smartlist_clear(pending_vote_list);
  2652. if (pending_consensus_signature_list) {
  2653. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
  2654. tor_free(cp));
  2655. smartlist_clear(pending_consensus_signature_list);
  2656. }
  2657. tor_free(pending_consensus_signatures);
  2658. dirvote_clear_pending_consensuses();
  2659. }
  2660. /** Return a newly allocated string containing the hex-encoded v3 authority
  2661. identity digest of every recognized v3 authority. */
  2662. static char *
  2663. list_v3_auth_ids(void)
  2664. {
  2665. smartlist_t *known_v3_keys = smartlist_new();
  2666. char *keys;
  2667. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  2668. dir_server_t *, ds,
  2669. if ((ds->type & V3_DIRINFO) &&
  2670. !tor_digest_is_zero(ds->v3_identity_digest))
  2671. smartlist_add(known_v3_keys,
  2672. tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
  2673. keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
  2674. SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
  2675. smartlist_free(known_v3_keys);
  2676. return keys;
  2677. }
  2678. /** Called when we have received a networkstatus vote in <b>vote_body</b>.
  2679. * Parse and validate it, and on success store it as a pending vote (which we
  2680. * then return). Return NULL on failure. Sets *<b>msg_out</b> and
  2681. * *<b>status_out</b> to an HTTP response and status code. (V3 authority
  2682. * only) */
  2683. pending_vote_t *
  2684. dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
  2685. {
  2686. networkstatus_t *vote;
  2687. networkstatus_voter_info_t *vi;
  2688. dir_server_t *ds;
  2689. pending_vote_t *pending_vote = NULL;
  2690. const char *end_of_vote = NULL;
  2691. int any_failed = 0;
  2692. tor_assert(vote_body);
  2693. tor_assert(msg_out);
  2694. tor_assert(status_out);
  2695. if (!pending_vote_list)
  2696. pending_vote_list = smartlist_new();
  2697. *status_out = 0;
  2698. *msg_out = NULL;
  2699. again:
  2700. vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
  2701. NS_TYPE_VOTE);
  2702. if (!end_of_vote)
  2703. end_of_vote = vote_body + strlen(vote_body);
  2704. if (!vote) {
  2705. log_warn(LD_DIR, "Couldn't parse vote: length was %d",
  2706. (int)strlen(vote_body));
  2707. *msg_out = "Unable to parse vote";
  2708. goto err;
  2709. }
  2710. tor_assert(smartlist_len(vote->voters) == 1);
  2711. vi = get_voter(vote);
  2712. {
  2713. int any_sig_good = 0;
  2714. SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
  2715. if (sig->good_signature)
  2716. any_sig_good = 1);
  2717. tor_assert(any_sig_good);
  2718. }
  2719. ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
  2720. if (!ds) {
  2721. char *keys = list_v3_auth_ids();
  2722. log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
  2723. "with authority key ID %s. "
  2724. "This key ID is not recognized. Known v3 key IDs are: %s",
  2725. vi->nickname, vi->address,
  2726. hex_str(vi->identity_digest, DIGEST_LEN), keys);
  2727. tor_free(keys);
  2728. *msg_out = "Vote not from a recognized v3 authority";
  2729. goto err;
  2730. }
  2731. tor_assert(vote->cert);
  2732. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  2733. vote->cert->signing_key_digest)) {
  2734. /* Hey, it's a new cert! */
  2735. trusted_dirs_load_certs_from_string(
  2736. vote->cert->cache_info.signed_descriptor_body,
  2737. 0 /* from_store */, 1 /*flush*/);
  2738. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  2739. vote->cert->signing_key_digest)) {
  2740. log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
  2741. }
  2742. }
  2743. /* Is it for the right period? */
  2744. if (vote->valid_after != voting_schedule.interval_starts) {
  2745. char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
  2746. format_iso_time(tbuf1, vote->valid_after);
  2747. format_iso_time(tbuf2, voting_schedule.interval_starts);
  2748. log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
  2749. "we were expecting %s", vi->address, tbuf1, tbuf2);
  2750. *msg_out = "Bad valid-after time";
  2751. goto err;
  2752. }
  2753. /* Fetch any new router descriptors we just learned about */
  2754. update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
  2755. /* Now see whether we already have a vote from this authority. */
  2756. SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
  2757. if (fast_memeq(v->vote->cert->cache_info.identity_digest,
  2758. vote->cert->cache_info.identity_digest,
  2759. DIGEST_LEN)) {
  2760. networkstatus_voter_info_t *vi_old = get_voter(v->vote);
  2761. if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
  2762. /* Ah, it's the same vote. Not a problem. */
  2763. log_info(LD_DIR, "Discarding a vote we already have (from %s).",
  2764. vi->address);
  2765. if (*status_out < 200)
  2766. *status_out = 200;
  2767. goto discard;
  2768. } else if (v->vote->published < vote->published) {
  2769. log_notice(LD_DIR, "Replacing an older pending vote from this "
  2770. "directory.");
  2771. cached_dir_decref(v->vote_body);
  2772. networkstatus_vote_free(v->vote);
  2773. v->vote_body = new_cached_dir(tor_strndup(vote_body,
  2774. end_of_vote-vote_body),
  2775. vote->published);
  2776. v->vote = vote;
  2777. if (end_of_vote &&
  2778. !strcmpstart(end_of_vote, "network-status-version"))
  2779. goto again;
  2780. if (*status_out < 200)
  2781. *status_out = 200;
  2782. if (!*msg_out)
  2783. *msg_out = "OK";
  2784. return v;
  2785. } else {
  2786. *msg_out = "Already have a newer pending vote";
  2787. goto err;
  2788. }
  2789. }
  2790. } SMARTLIST_FOREACH_END(v);
  2791. pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
  2792. pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
  2793. end_of_vote-vote_body),
  2794. vote->published);
  2795. pending_vote->vote = vote;
  2796. smartlist_add(pending_vote_list, pending_vote);
  2797. if (!strcmpstart(end_of_vote, "network-status-version ")) {
  2798. vote_body = end_of_vote;
  2799. goto again;
  2800. }
  2801. goto done;
  2802. err:
  2803. any_failed = 1;
  2804. if (!*msg_out)
  2805. *msg_out = "Error adding vote";
  2806. if (*status_out < 400)
  2807. *status_out = 400;
  2808. discard:
  2809. networkstatus_vote_free(vote);
  2810. if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
  2811. vote_body = end_of_vote;
  2812. goto again;
  2813. }
  2814. done:
  2815. if (*status_out < 200)
  2816. *status_out = 200;
  2817. if (!*msg_out) {
  2818. if (!any_failed && !pending_vote) {
  2819. *msg_out = "Duplicate discarded";
  2820. } else {
  2821. *msg_out = "ok";
  2822. }
  2823. }
  2824. return any_failed ? NULL : pending_vote;
  2825. }
  2826. /** Try to compute a v3 networkstatus consensus from the currently pending
  2827. * votes. Return 0 on success, -1 on failure. Store the consensus in
  2828. * pending_consensus: it won't be ready to be published until we have
  2829. * everybody else's signatures collected too. (V3 Authority only) */
  2830. static int
  2831. dirvote_compute_consensuses(void)
  2832. {
  2833. /* Have we got enough votes to try? */
  2834. int n_votes, n_voters, n_vote_running = 0;
  2835. smartlist_t *votes = NULL, *votestrings = NULL;
  2836. char *consensus_body = NULL, *signatures = NULL, *votefile;
  2837. networkstatus_t *consensus = NULL;
  2838. authority_cert_t *my_cert;
  2839. pending_consensus_t pending[N_CONSENSUS_FLAVORS];
  2840. int flav;
  2841. memset(pending, 0, sizeof(pending));
  2842. if (!pending_vote_list)
  2843. pending_vote_list = smartlist_new();
  2844. n_voters = get_n_authorities(V3_DIRINFO);
  2845. n_votes = smartlist_len(pending_vote_list);
  2846. if (n_votes <= n_voters/2) {
  2847. log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
  2848. "%d of %d", n_votes, n_voters/2+1);
  2849. goto err;
  2850. }
  2851. tor_assert(pending_vote_list);
  2852. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  2853. if (smartlist_contains_string(v->vote->known_flags, "Running"))
  2854. n_vote_running++;
  2855. });
  2856. if (!n_vote_running) {
  2857. /* See task 1066. */
  2858. log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
  2859. "and publishing a consensus without Running nodes "
  2860. "would make many clients stop working. Not "
  2861. "generating a consensus!");
  2862. goto err;
  2863. }
  2864. if (!(my_cert = get_my_v3_authority_cert())) {
  2865. log_warn(LD_DIR, "Can't generate consensus without a certificate.");
  2866. goto err;
  2867. }
  2868. votes = smartlist_new();
  2869. votestrings = smartlist_new();
  2870. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
  2871. {
  2872. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  2873. c->bytes = v->vote_body->dir;
  2874. c->len = v->vote_body->dir_len;
  2875. smartlist_add(votestrings, c); /* collect strings to write to disk */
  2876. smartlist_add(votes, v->vote); /* collect votes to compute consensus */
  2877. });
  2878. votefile = get_datadir_fname("v3-status-votes");
  2879. write_chunks_to_file(votefile, votestrings, 0);
  2880. tor_free(votefile);
  2881. SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
  2882. smartlist_free(votestrings);
  2883. {
  2884. char legacy_dbuf[DIGEST_LEN];
  2885. crypto_pk_t *legacy_sign=NULL;
  2886. char *legacy_id_digest = NULL;
  2887. int n_generated = 0;
  2888. if (get_options()->V3AuthUseLegacyKey) {
  2889. authority_cert_t *cert = get_my_v3_legacy_cert();
  2890. legacy_sign = get_my_v3_legacy_signing_key();
  2891. if (cert) {
  2892. if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
  2893. log_warn(LD_BUG,
  2894. "Unable to compute digest of legacy v3 identity key");
  2895. } else {
  2896. legacy_id_digest = legacy_dbuf;
  2897. }
  2898. }
  2899. }
  2900. for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  2901. const char *flavor_name = networkstatus_get_flavor_name(flav);
  2902. consensus_body = networkstatus_compute_consensus(
  2903. votes, n_voters,
  2904. my_cert->identity_key,
  2905. get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
  2906. flav);
  2907. if (!consensus_body) {
  2908. log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
  2909. flavor_name);
  2910. continue;
  2911. }
  2912. consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
  2913. NS_TYPE_CONSENSUS);
  2914. if (!consensus) {
  2915. log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
  2916. flavor_name);
  2917. tor_free(consensus_body);
  2918. continue;
  2919. }
  2920. /* 'Check' our own signature, to mark it valid. */
  2921. networkstatus_check_consensus_signature(consensus, -1);
  2922. pending[flav].body = consensus_body;
  2923. pending[flav].consensus = consensus;
  2924. n_generated++;
  2925. consensus_body = NULL;
  2926. consensus = NULL;
  2927. }
  2928. if (!n_generated) {
  2929. log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
  2930. goto err;
  2931. }
  2932. }
  2933. signatures = get_detached_signatures_from_pending_consensuses(
  2934. pending, N_CONSENSUS_FLAVORS);
  2935. if (!signatures) {
  2936. log_warn(LD_DIR, "Couldn't extract signatures.");
  2937. goto err;
  2938. }
  2939. dirvote_clear_pending_consensuses();
  2940. memcpy(pending_consensuses, pending, sizeof(pending));
  2941. tor_free(pending_consensus_signatures);
  2942. pending_consensus_signatures = signatures;
  2943. if (pending_consensus_signature_list) {
  2944. int n_sigs = 0;
  2945. /* we may have gotten signatures for this consensus before we built
  2946. * it ourself. Add them now. */
  2947. SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
  2948. const char *msg = NULL;
  2949. int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
  2950. "pending", &msg);
  2951. if (r >= 0)
  2952. n_sigs += r;
  2953. else
  2954. log_warn(LD_DIR,
  2955. "Could not add queued signature to new consensus: %s",
  2956. msg);
  2957. tor_free(sig);
  2958. } SMARTLIST_FOREACH_END(sig);
  2959. if (n_sigs)
  2960. log_notice(LD_DIR, "Added %d pending signatures while building "
  2961. "consensus.", n_sigs);
  2962. smartlist_clear(pending_consensus_signature_list);
  2963. }
  2964. log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
  2965. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
  2966. ROUTER_PURPOSE_GENERAL,
  2967. V3_DIRINFO,
  2968. pending_consensus_signatures,
  2969. strlen(pending_consensus_signatures), 0);
  2970. log_notice(LD_DIR, "Signature(s) posted.");
  2971. smartlist_free(votes);
  2972. return 0;
  2973. err:
  2974. smartlist_free(votes);
  2975. tor_free(consensus_body);
  2976. tor_free(signatures);
  2977. networkstatus_vote_free(consensus);
  2978. return -1;
  2979. }
  2980. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  2981. * signatures on the currently pending consensus. Add them to <b>pc</b>
  2982. * as appropriate. Return the number of signatures added. (?) */
  2983. static int
  2984. dirvote_add_signatures_to_pending_consensus(
  2985. pending_consensus_t *pc,
  2986. ns_detached_signatures_t *sigs,
  2987. const char *source,
  2988. int severity,
  2989. const char **msg_out)
  2990. {
  2991. const char *flavor_name;
  2992. int r = -1;
  2993. /* Only call if we have a pending consensus right now. */
  2994. tor_assert(pc->consensus);
  2995. tor_assert(pc->body);
  2996. tor_assert(pending_consensus_signatures);
  2997. flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
  2998. *msg_out = NULL;
  2999. {
  3000. smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
  3001. log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
  3002. sig_list ? smartlist_len(sig_list) : 0, flavor_name);
  3003. }
  3004. r = networkstatus_add_detached_signatures(pc->consensus, sigs,
  3005. source, severity, msg_out);
  3006. log_info(LD_DIR,"Added %d signatures to consensus.", r);
  3007. if (r >= 1) {
  3008. char *new_signatures =
  3009. networkstatus_format_signatures(pc->consensus, 0);
  3010. char *dst, *dst_end;
  3011. size_t new_consensus_len;
  3012. if (!new_signatures) {
  3013. *msg_out = "No signatures to add";
  3014. goto err;
  3015. }
  3016. new_consensus_len =
  3017. strlen(pc->body) + strlen(new_signatures) + 1;
  3018. pc->body = tor_realloc(pc->body, new_consensus_len);
  3019. dst_end = pc->body + new_consensus_len;
  3020. dst = strstr(pc->body, "directory-signature ");
  3021. tor_assert(dst);
  3022. strlcpy(dst, new_signatures, dst_end-dst);
  3023. /* We remove this block once it has failed to crash for a while. But
  3024. * unless it shows up in profiles, we're probably better leaving it in,
  3025. * just in case we break detached signature processing at some point. */
  3026. {
  3027. networkstatus_t *v = networkstatus_parse_vote_from_string(
  3028. pc->body, NULL,
  3029. NS_TYPE_CONSENSUS);
  3030. tor_assert(v);
  3031. networkstatus_vote_free(v);
  3032. }
  3033. *msg_out = "Signatures added";
  3034. tor_free(new_signatures);
  3035. } else if (r == 0) {
  3036. *msg_out = "Signatures ignored";
  3037. } else {
  3038. goto err;
  3039. }
  3040. goto done;
  3041. err:
  3042. if (!*msg_out)
  3043. *msg_out = "Unrecognized error while adding detached signatures.";
  3044. done:
  3045. return r;
  3046. }
  3047. static int
  3048. dirvote_add_signatures_to_all_pending_consensuses(
  3049. const char *detached_signatures_body,
  3050. const char *source,
  3051. const char **msg_out)
  3052. {
  3053. int r=0, i, n_added = 0, errors = 0;
  3054. ns_detached_signatures_t *sigs;
  3055. tor_assert(detached_signatures_body);
  3056. tor_assert(msg_out);
  3057. tor_assert(pending_consensus_signatures);
  3058. if (!(sigs = networkstatus_parse_detached_signatures(
  3059. detached_signatures_body, NULL))) {
  3060. *msg_out = "Couldn't parse detached signatures.";
  3061. goto err;
  3062. }
  3063. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  3064. int res;
  3065. int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
  3066. pending_consensus_t *pc = &pending_consensuses[i];
  3067. if (!pc->consensus)
  3068. continue;
  3069. res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
  3070. severity, msg_out);
  3071. if (res < 0)
  3072. errors++;
  3073. else
  3074. n_added += res;
  3075. }
  3076. if (errors && !n_added) {
  3077. r = -1;
  3078. goto err;
  3079. }
  3080. if (n_added && pending_consensuses[FLAV_NS].consensus) {
  3081. char *new_detached =
  3082. get_detached_signatures_from_pending_consensuses(
  3083. pending_consensuses, N_CONSENSUS_FLAVORS);
  3084. if (new_detached) {
  3085. tor_free(pending_consensus_signatures);
  3086. pending_consensus_signatures = new_detached;
  3087. }
  3088. }
  3089. r = n_added;
  3090. goto done;
  3091. err:
  3092. if (!*msg_out)
  3093. *msg_out = "Unrecognized error while adding detached signatures.";
  3094. done:
  3095. ns_detached_signatures_free(sigs);
  3096. /* XXXX NM Check how return is used. We can now have an error *and*
  3097. signatures added. */
  3098. return r;
  3099. }
  3100. /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
  3101. * signatures on the currently pending consensus. Add them to the pending
  3102. * consensus (if we have one); otherwise queue them until we have a
  3103. * consensus. Return negative on failure, nonnegative on success. */
  3104. int
  3105. dirvote_add_signatures(const char *detached_signatures_body,
  3106. const char *source,
  3107. const char **msg)
  3108. {
  3109. if (pending_consensuses[FLAV_NS].consensus) {
  3110. log_notice(LD_DIR, "Got a signature from %s. "
  3111. "Adding it to the pending consensus.", source);
  3112. return dirvote_add_signatures_to_all_pending_consensuses(
  3113. detached_signatures_body, source, msg);
  3114. } else {
  3115. log_notice(LD_DIR, "Got a signature from %s. "
  3116. "Queuing it for the next consensus.", source);
  3117. if (!pending_consensus_signature_list)
  3118. pending_consensus_signature_list = smartlist_new();
  3119. smartlist_add(pending_consensus_signature_list,
  3120. tor_strdup(detached_signatures_body));
  3121. *msg = "Signature queued";
  3122. return 0;
  3123. }
  3124. }
  3125. /** Replace the consensus that we're currently serving with the one that we've
  3126. * been building. (V3 Authority only) */
  3127. static int
  3128. dirvote_publish_consensus(void)
  3129. {
  3130. int i;
  3131. /* Now remember all the other consensuses as if we were a directory cache. */
  3132. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  3133. pending_consensus_t *pending = &pending_consensuses[i];
  3134. const char *name;
  3135. name = networkstatus_get_flavor_name(i);
  3136. tor_assert(name);
  3137. if (!pending->consensus ||
  3138. networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
  3139. log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
  3140. continue;
  3141. }
  3142. if (networkstatus_set_current_consensus(pending->body, name, 0))
  3143. log_warn(LD_DIR, "Error publishing %s consensus", name);
  3144. else
  3145. log_notice(LD_DIR, "Published %s consensus", name);
  3146. }
  3147. return 0;
  3148. }
  3149. /** Release all static storage held in dirvote.c */
  3150. void
  3151. dirvote_free_all(void)
  3152. {
  3153. dirvote_clear_votes(1);
  3154. /* now empty as a result of dirvote_clear_votes(). */
  3155. smartlist_free(pending_vote_list);
  3156. pending_vote_list = NULL;
  3157. smartlist_free(previous_vote_list);
  3158. previous_vote_list = NULL;
  3159. dirvote_clear_pending_consensuses();
  3160. tor_free(pending_consensus_signatures);
  3161. if (pending_consensus_signature_list) {
  3162. /* now empty as a result of dirvote_clear_votes(). */
  3163. smartlist_free(pending_consensus_signature_list);
  3164. pending_consensus_signature_list = NULL;
  3165. }
  3166. }
  3167. /* ====
  3168. * Access to pending items.
  3169. * ==== */
  3170. /** Return the body of the consensus that we're currently trying to build. */
  3171. const char *
  3172. dirvote_get_pending_consensus(consensus_flavor_t flav)
  3173. {
  3174. tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
  3175. return pending_consensuses[flav].body;
  3176. }
  3177. /** Return the signatures that we know for the consensus that we're currently
  3178. * trying to build. */
  3179. const char *
  3180. dirvote_get_pending_detached_signatures(void)
  3181. {
  3182. return pending_consensus_signatures;
  3183. }
  3184. /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
  3185. * vote for the authority with the v3 authority identity key digest <b>fp</b>;
  3186. * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
  3187. * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
  3188. * false, do not consider any votes for a consensus that's already been built.
  3189. * If <b>include_pending</b> is false, do not consider any votes for the
  3190. * consensus that's in progress. May return NULL if we have no vote for the
  3191. * authority in question. */
  3192. const cached_dir_t *
  3193. dirvote_get_vote(const char *fp, int flags)
  3194. {
  3195. int by_id = flags & DGV_BY_ID;
  3196. const int include_pending = flags & DGV_INCLUDE_PENDING;
  3197. const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
  3198. if (!pending_vote_list && !previous_vote_list)
  3199. return NULL;
  3200. if (fp == NULL) {
  3201. authority_cert_t *c = get_my_v3_authority_cert();
  3202. if (c) {
  3203. fp = c->cache_info.identity_digest;
  3204. by_id = 1;
  3205. } else
  3206. return NULL;
  3207. }
  3208. if (by_id) {
  3209. if (pending_vote_list && include_pending) {
  3210. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  3211. if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  3212. return pv->vote_body);
  3213. }
  3214. if (previous_vote_list && include_previous) {
  3215. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  3216. if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
  3217. return pv->vote_body);
  3218. }
  3219. } else {
  3220. if (pending_vote_list && include_pending) {
  3221. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  3222. if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  3223. return pv->vote_body);
  3224. }
  3225. if (previous_vote_list && include_previous) {
  3226. SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
  3227. if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
  3228. return pv->vote_body);
  3229. }
  3230. }
  3231. return NULL;
  3232. }
  3233. /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
  3234. * according to <b>consensus_method</b>.
  3235. **/
  3236. microdesc_t *
  3237. dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
  3238. {
  3239. microdesc_t *result = NULL;
  3240. char *key = NULL, *summary = NULL, *family = NULL;
  3241. size_t keylen;
  3242. smartlist_t *chunks = smartlist_new();
  3243. char *output = NULL;
  3244. if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
  3245. goto done;
  3246. summary = policy_summarize(ri->exit_policy, AF_INET);
  3247. if (ri->declared_family)
  3248. family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
  3249. smartlist_add_asprintf(chunks, "onion-key\n%s", key);
  3250. if (consensus_method >= MIN_METHOD_FOR_NTOR_KEY &&
  3251. ri->onion_curve25519_pkey) {
  3252. char kbuf[128];
  3253. base64_encode(kbuf, sizeof(kbuf),
  3254. (const char*)ri->onion_curve25519_pkey->public_key,
  3255. CURVE25519_PUBKEY_LEN);
  3256. smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
  3257. }
  3258. if (consensus_method >= MIN_METHOD_FOR_A_LINES &&
  3259. !tor_addr_is_null(&ri->ipv6_addr) && ri->ipv6_orport)
  3260. smartlist_add_asprintf(chunks, "a %s\n",
  3261. fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
  3262. if (family)
  3263. smartlist_add_asprintf(chunks, "family %s\n", family);
  3264. if (summary && strcmp(summary, "reject 1-65535"))
  3265. smartlist_add_asprintf(chunks, "p %s\n", summary);
  3266. if (consensus_method >= MIN_METHOD_FOR_P6_LINES &&
  3267. ri->ipv6_exit_policy) {
  3268. /* XXXX024 This doesn't match proposal 208, which says these should
  3269. * be taken unchanged from the routerinfo. That's bogosity, IMO:
  3270. * the proposal should have said to do this instead.*/
  3271. char *p6 = write_short_policy(ri->ipv6_exit_policy);
  3272. if (p6 && strcmp(p6, "reject 1-65535"))
  3273. smartlist_add_asprintf(chunks, "p6 %s\n", p6);
  3274. tor_free(p6);
  3275. }
  3276. output = smartlist_join_strings(chunks, "", 0, NULL);
  3277. {
  3278. smartlist_t *lst = microdescs_parse_from_string(output,
  3279. output+strlen(output), 0, 1);
  3280. if (smartlist_len(lst) != 1) {
  3281. log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
  3282. SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
  3283. smartlist_free(lst);
  3284. goto done;
  3285. }
  3286. result = smartlist_get(lst, 0);
  3287. smartlist_free(lst);
  3288. }
  3289. done:
  3290. tor_free(output);
  3291. tor_free(key);
  3292. tor_free(summary);
  3293. tor_free(family);
  3294. if (chunks) {
  3295. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  3296. smartlist_free(chunks);
  3297. }
  3298. return result;
  3299. }
  3300. /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
  3301. * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
  3302. * in <b>out</b>. Return -1 on failure and the number of characters written
  3303. * on success. */
  3304. ssize_t
  3305. dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
  3306. const microdesc_t *md,
  3307. int consensus_method_low,
  3308. int consensus_method_high)
  3309. {
  3310. ssize_t ret = -1;
  3311. char d64[BASE64_DIGEST256_LEN+1];
  3312. char *microdesc_consensus_methods =
  3313. make_consensus_method_list(consensus_method_low,
  3314. consensus_method_high,
  3315. ",");
  3316. tor_assert(microdesc_consensus_methods);
  3317. if (digest256_to_base64(d64, md->digest)<0)
  3318. goto out;
  3319. if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
  3320. microdesc_consensus_methods, d64)<0)
  3321. goto out;
  3322. ret = strlen(out_buf);
  3323. out:
  3324. tor_free(microdesc_consensus_methods);
  3325. return ret;
  3326. }
  3327. /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
  3328. * the digest algorithm <b>alg</b>, decode it and copy it into
  3329. * <b>digest256_out</b> and return 0. Otherwise return -1. */
  3330. int
  3331. vote_routerstatus_find_microdesc_hash(char *digest256_out,
  3332. const vote_routerstatus_t *vrs,
  3333. int method,
  3334. digest_algorithm_t alg)
  3335. {
  3336. /* XXXX only returns the sha256 method. */
  3337. const vote_microdesc_hash_t *h;
  3338. char mstr[64];
  3339. size_t mlen;
  3340. char dstr[64];
  3341. tor_snprintf(mstr, sizeof(mstr), "%d", method);
  3342. mlen = strlen(mstr);
  3343. tor_snprintf(dstr, sizeof(dstr), " %s=",
  3344. crypto_digest_algorithm_get_name(alg));
  3345. for (h = vrs->microdesc; h; h = h->next) {
  3346. const char *cp = h->microdesc_hash_line;
  3347. size_t num_len;
  3348. /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
  3349. * the first part. */
  3350. while (1) {
  3351. num_len = strspn(cp, "1234567890");
  3352. if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
  3353. /* This is the line. */
  3354. char buf[BASE64_DIGEST256_LEN+1];
  3355. /* XXXX ignores extraneous stuff if the digest is too long. This
  3356. * seems harmless enough, right? */
  3357. cp = strstr(cp, dstr);
  3358. if (!cp)
  3359. return -1;
  3360. cp += strlen(dstr);
  3361. strlcpy(buf, cp, sizeof(buf));
  3362. return digest256_from_base64(digest256_out, buf);
  3363. }
  3364. if (num_len == 0 || cp[num_len] != ',')
  3365. break;
  3366. cp += num_len + 1;
  3367. }
  3368. }
  3369. return -1;
  3370. }