dirvote.c 114 KB

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