dirvote.c 98 KB

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