dirvote.c 119 KB

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