dirvote.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dirvote_c_id[] =
  6. "$Id$";
  7. #define DIRVOTE_PRIVATE
  8. #include "or.h"
  9. /**
  10. * \file dirvote.c
  11. * \brief Functions to compute directory consensus, and schedule voting.
  12. **/
  13. static int dirvote_add_signatures_to_pending_consensus(
  14. const char *detached_signatures_body,
  15. const char **msg_out);
  16. static char *list_v3_auth_ids(void);
  17. /* =====
  18. * Voting and consensus generation
  19. * ===== */
  20. /** Clear all storage held in <b>ns</b>. */
  21. void
  22. networkstatus_vote_free(networkstatus_vote_t *ns)
  23. {
  24. if (!ns)
  25. return;
  26. tor_free(ns->client_versions);
  27. tor_free(ns->server_versions);
  28. if (ns->known_flags) {
  29. SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
  30. smartlist_free(ns->known_flags);
  31. }
  32. if (ns->voters) {
  33. SMARTLIST_FOREACH(ns->voters, networkstatus_voter_info_t *, voter,
  34. {
  35. tor_free(voter->nickname);
  36. tor_free(voter->address);
  37. tor_free(voter->contact);
  38. });
  39. smartlist_free(ns->voters);
  40. }
  41. if (ns->cert)
  42. authority_cert_free(ns->cert);
  43. if (ns->routerstatus_list) {
  44. if (ns->is_vote) {
  45. SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
  46. {
  47. tor_free(rs->version);
  48. tor_free(rs);
  49. });
  50. } else {
  51. SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
  52. tor_free(rs));
  53. }
  54. smartlist_free(ns->routerstatus_list);
  55. }
  56. memset(ns, 11, sizeof(*ns));
  57. tor_free(ns);
  58. }
  59. /** Return the voter info from <b>vote</b> for the voter whose identity digest
  60. * is <b>identity</b>, or NULL if no such voter is associated with
  61. * <b>vote</b>. */
  62. networkstatus_voter_info_t *
  63. networkstatus_get_voter_by_id(networkstatus_vote_t *vote,
  64. const char *identity)
  65. {
  66. if (!vote || !vote->voters)
  67. return NULL;
  68. SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
  69. if (!memcmp(voter->identity_digest, identity, DIGEST_LEN))
  70. return voter);
  71. return NULL;
  72. }
  73. /** Helper for sorting a list of time_t*. */
  74. static int
  75. _compare_times(const void **_a, const void **_b)
  76. {
  77. const time_t *a = *_a, *b = *_b;
  78. if (*a<*b)
  79. return -1;
  80. else if (*a>*b)
  81. return 1;
  82. else
  83. return 0;
  84. }
  85. /** Helper for sorting a list of int*. */
  86. static int
  87. _compare_ints(const void **_a, const void **_b)
  88. {
  89. const int *a = *_a, *b = *_b;
  90. if (*a<*b)
  91. return -1;
  92. else if (*a>*b)
  93. return 1;
  94. else
  95. return 0;
  96. }
  97. /** Given a list of one or more time_t*, return the (low) median. */
  98. /*static*/ time_t
  99. median_time(smartlist_t *times)
  100. {
  101. int idx;
  102. tor_assert(smartlist_len(times));
  103. smartlist_sort(times, _compare_times);
  104. idx = (smartlist_len(times)-1)/2;
  105. return *(time_t*)smartlist_get(times, idx);
  106. }
  107. /** Given a list of one or more int*, return the (low) median. */
  108. /*static*/ int
  109. median_int(smartlist_t *ints)
  110. {
  111. int idx;
  112. tor_assert(smartlist_len(ints));
  113. smartlist_sort(ints, _compare_ints);
  114. idx = (smartlist_len(ints)-1)/2;
  115. return *(int*)smartlist_get(ints, idx);
  116. }
  117. /** Given a vote <b>vote</b> (not a consensus!), return its associated
  118. * networkstatus_voter_info_t.*/
  119. static networkstatus_voter_info_t *
  120. get_voter(const networkstatus_vote_t *vote)
  121. {
  122. tor_assert(vote);
  123. tor_assert(vote->is_vote);
  124. tor_assert(vote->voters);
  125. tor_assert(smartlist_len(vote->voters) == 1);
  126. return smartlist_get(vote->voters, 0);
  127. }
  128. /** Helper for sorting networkstatus_vote_t votes (not consensuses) by the
  129. * hash of their voters' identity digests. */
  130. static int
  131. _compare_votes_by_authority_id(const void **_a, const void **_b)
  132. {
  133. const networkstatus_vote_t *a = *_a, *b = *_b;
  134. return memcmp(get_voter(a)->identity_digest,
  135. get_voter(b)->identity_digest, DIGEST_LEN);
  136. }
  137. /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
  138. * that occurs more than <b>min</b> times. */
  139. static void
  140. get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
  141. {
  142. char *cur = NULL;
  143. int count = 0;
  144. SMARTLIST_FOREACH(in, char *, cp,
  145. {
  146. if (cur && !strcmp(cp, cur)) {
  147. ++count;
  148. } else {
  149. if (count > min)
  150. smartlist_add(out, cur);
  151. cur = cp;
  152. count = 1;
  153. }
  154. });
  155. if (count > min)
  156. smartlist_add(out, cur);
  157. }
  158. /** Given a sorted list of strings <b>lst</b>, return the member that appears
  159. * most. Break ties in favor of later-occurring members. */
  160. static const char *
  161. get_most_frequent_member(smartlist_t *lst)
  162. {
  163. const char *most_frequent = NULL;
  164. int most_frequent_count = 0;
  165. const char *cur = NULL;
  166. int count = 0;
  167. SMARTLIST_FOREACH(lst, const char *, s,
  168. {
  169. if (cur && !strcmp(s, cur)) {
  170. ++count;
  171. } else {
  172. if (count >= most_frequent_count) {
  173. most_frequent = cur;
  174. most_frequent_count = count;
  175. }
  176. cur = s;
  177. count = 1;
  178. }
  179. });
  180. if (count >= most_frequent_count) {
  181. most_frequent = cur;
  182. most_frequent_count = count;
  183. }
  184. return most_frequent;
  185. }
  186. /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
  187. * that come from the same routerinfo, with the same derived elements.
  188. */
  189. static int
  190. compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
  191. {
  192. int r;
  193. if ((r = memcmp(a->status.identity_digest, b->status.identity_digest,
  194. DIGEST_LEN)))
  195. return r;
  196. if ((r = memcmp(a->status.descriptor_digest, b->status.descriptor_digest,
  197. DIGEST_LEN)))
  198. return r;
  199. if ((r = (b->status.published_on - a->status.published_on)))
  200. return r;
  201. if ((r = strcmp(b->status.nickname, a->status.nickname)))
  202. return r;
  203. if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
  204. return r;
  205. if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
  206. return r;
  207. if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
  208. return r;
  209. return 0;
  210. }
  211. /** Helper for sorting routerlists based on compare_vote_rs. */
  212. static int
  213. _compare_vote_rs(const void **_a, const void **_b)
  214. {
  215. const vote_routerstatus_t *a = *_a, *b = *_b;
  216. return compare_vote_rs(a,b);
  217. }
  218. /** Given a list of vote_routerstatus_t, all for the same router identity,
  219. * return whichever is most frequent, breaking ties in favor of more
  220. * recently published vote_routerstatus_t.
  221. */
  222. static vote_routerstatus_t *
  223. compute_routerstatus_consensus(smartlist_t *votes)
  224. {
  225. vote_routerstatus_t *most = NULL, *cur = NULL;
  226. int most_n = 0, cur_n = 0;
  227. time_t most_published = 0;
  228. smartlist_sort(votes, _compare_vote_rs);
  229. SMARTLIST_FOREACH(votes, vote_routerstatus_t *, rs,
  230. {
  231. if (cur && !compare_vote_rs(cur, rs)) {
  232. ++cur_n;
  233. } else {
  234. if (cur_n > most_n ||
  235. (cur && cur_n == most_n &&
  236. cur->status.published_on > most_published)) {
  237. most = cur;
  238. most_n = cur_n;
  239. most_published = cur->status.published_on;
  240. }
  241. cur_n = 1;
  242. cur = rs;
  243. }
  244. });
  245. if (cur_n > most_n ||
  246. (cur && cur_n == most_n && cur->status.published_on > most_published)) {
  247. most = cur;
  248. most_n = cur_n;
  249. most_published = cur->status.published_on;
  250. }
  251. tor_assert(most);
  252. return most;
  253. }
  254. /** Given a list of strings in <b>lst</b>, set the DIGEST_LEN-byte digest at
  255. * <b>digest_out</b> to the hash of the concatenation of those strings. */
  256. static void
  257. hash_list_members(char *digest_out, smartlist_t *lst)
  258. {
  259. crypto_digest_env_t *d = crypto_new_digest_env();
  260. SMARTLIST_FOREACH(lst, const char *, cp,
  261. crypto_digest_add_bytes(d, cp, strlen(cp)));
  262. crypto_digest_get_digest(d, digest_out, DIGEST_LEN);
  263. crypto_free_digest_env(d);
  264. }
  265. /** Given a list of vote networkstatus_vote_t in <b>votes</b>, our public
  266. * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
  267. * and the number of <b>total_authorities</b> that we believe exist in our
  268. * voting quorum, generate the text of a new v3 consensus vote, and return the
  269. * value in a newly allocated string.
  270. *
  271. * Note: this function DOES NOT check whether the votes are from
  272. * recognized authorities. (dirvote_add_vote does that.) */
  273. char *
  274. networkstatus_compute_consensus(smartlist_t *votes,
  275. int total_authorities,
  276. crypto_pk_env_t *identity_key,
  277. crypto_pk_env_t *signing_key)
  278. {
  279. smartlist_t *chunks;
  280. char *result = NULL;
  281. time_t valid_after, fresh_until, valid_until;
  282. int vote_seconds, dist_seconds;
  283. char *client_versions = NULL, *server_versions = NULL;
  284. smartlist_t *flags;
  285. tor_assert(total_authorities >= smartlist_len(votes));
  286. if (!smartlist_len(votes)) {
  287. log_warn(LD_DIR, "Can't compute a consensus from no votes.");
  288. return NULL;
  289. }
  290. flags = smartlist_create();
  291. /* Compute medians of time-related things, and figure out how many
  292. * routers we might need to talk about. */
  293. {
  294. smartlist_t *va_times = smartlist_create();
  295. smartlist_t *fu_times = smartlist_create();
  296. smartlist_t *vu_times = smartlist_create();
  297. smartlist_t *votesec_list = smartlist_create();
  298. smartlist_t *distsec_list = smartlist_create();
  299. int n_versioning_clients = 0, n_versioning_servers = 0;
  300. smartlist_t *combined_client_versions = smartlist_create();
  301. smartlist_t *combined_server_versions = smartlist_create();
  302. int j;
  303. SMARTLIST_FOREACH(votes, networkstatus_vote_t *, v,
  304. {
  305. tor_assert(v->is_vote);
  306. smartlist_add(va_times, &v->valid_after);
  307. smartlist_add(fu_times, &v->fresh_until);
  308. smartlist_add(vu_times, &v->valid_until);
  309. smartlist_add(votesec_list, &v->vote_seconds);
  310. smartlist_add(distsec_list, &v->dist_seconds);
  311. if (v->client_versions) {
  312. smartlist_t *cv = smartlist_create();
  313. ++n_versioning_clients;
  314. smartlist_split_string(cv, v->client_versions, ",",
  315. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  316. sort_version_list(cv, 1);
  317. smartlist_add_all(combined_client_versions, cv);
  318. smartlist_free(cv); /* elements get freed later. */
  319. }
  320. if (v->server_versions) {
  321. smartlist_t *sv = smartlist_create();
  322. ++n_versioning_servers;
  323. smartlist_split_string(sv, v->server_versions, ",",
  324. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  325. sort_version_list(sv, 1);
  326. smartlist_add_all(combined_server_versions, sv);
  327. smartlist_free(sv); /* elements get freed later. */
  328. }
  329. SMARTLIST_FOREACH(v->known_flags, const char *, cp,
  330. smartlist_add(flags, tor_strdup(cp)));
  331. });
  332. valid_after = median_time(va_times);
  333. fresh_until = median_time(fu_times);
  334. valid_until = median_time(vu_times);
  335. vote_seconds = median_int(votesec_list);
  336. dist_seconds = median_int(distsec_list);
  337. /*
  338. SMARTLIST_FOREACH(va_times, int*, i,
  339. printf("VA: %d\n", *i));
  340. SMARTLIST_FOREACH(fu_times, int*, i,
  341. printf("FU: %d\n", *i));
  342. printf("%d..%d\n", (int)valid_after, (int)valid_until);
  343. */
  344. tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
  345. tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
  346. tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
  347. tor_assert(dist_seconds >= MIN_DIST_SECONDS);
  348. for (j = 0; j < 2; ++j) {
  349. smartlist_t *lst =
  350. j ? combined_server_versions : combined_client_versions;
  351. int min = (j ? n_versioning_servers : n_versioning_clients) / 2;
  352. smartlist_t *good = smartlist_create();
  353. char *res;
  354. sort_version_list(lst, 0);
  355. get_frequent_members(good, lst, min);
  356. res = smartlist_join_strings(good, ",", 0, NULL);
  357. if (j)
  358. server_versions = res;
  359. else
  360. client_versions = res;
  361. SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
  362. smartlist_free(good);
  363. smartlist_free(lst);
  364. }
  365. smartlist_sort_strings(flags);
  366. smartlist_uniq_strings(flags);
  367. smartlist_free(va_times);
  368. smartlist_free(fu_times);
  369. smartlist_free(vu_times);
  370. smartlist_free(votesec_list);
  371. smartlist_free(distsec_list);
  372. }
  373. chunks = smartlist_create();
  374. {
  375. char buf[1024];
  376. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  377. vu_buf[ISO_TIME_LEN+1];
  378. char *flaglist;
  379. format_iso_time(va_buf, valid_after);
  380. format_iso_time(fu_buf, fresh_until);
  381. format_iso_time(vu_buf, valid_until);
  382. flaglist = smartlist_join_strings(flags, " ", 0, NULL);
  383. tor_snprintf(buf, sizeof(buf),
  384. "network-status-version 3\n"
  385. "vote-status consensus\n"
  386. "valid-after %s\n"
  387. "fresh-until %s\n"
  388. "valid-until %s\n"
  389. "voting-delay %d %d\n"
  390. "client-versions %s\n"
  391. "server-versions %s\n"
  392. "known-flags %s\n",
  393. va_buf, fu_buf, vu_buf,
  394. vote_seconds, dist_seconds,
  395. client_versions, server_versions, flaglist);
  396. smartlist_add(chunks, tor_strdup(buf));
  397. tor_free(flaglist);
  398. }
  399. /* Sort the votes. */
  400. smartlist_sort(votes, _compare_votes_by_authority_id);
  401. /* Add the authority sections. */
  402. SMARTLIST_FOREACH(votes, networkstatus_vote_t *, v,
  403. {
  404. char buf[1024];
  405. struct in_addr in;
  406. char ip[INET_NTOA_BUF_LEN];
  407. char fingerprint[HEX_DIGEST_LEN+1];
  408. char votedigest[HEX_DIGEST_LEN+1];
  409. networkstatus_voter_info_t *voter = get_voter(v);
  410. in.s_addr = htonl(voter->addr);
  411. tor_inet_ntoa(&in, ip, sizeof(ip));
  412. base16_encode(fingerprint, sizeof(fingerprint), voter->identity_digest,
  413. DIGEST_LEN);
  414. base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
  415. DIGEST_LEN);
  416. tor_snprintf(buf, sizeof(buf),
  417. "dir-source %s %s %s %s %d %d\n"
  418. "contact %s\n"
  419. "vote-digest %s\n",
  420. voter->nickname, fingerprint, voter->address, ip,
  421. voter->dir_port,
  422. voter->or_port,
  423. voter->contact,
  424. votedigest);
  425. smartlist_add(chunks, tor_strdup(buf));
  426. });
  427. /* Add the actual router entries. */
  428. {
  429. int *index; /* index[j] is the current index into votes[j]. */
  430. int *size; /* size[j] is the number of routerstatuses in votes[j]. */
  431. int *flag_counts; /* The number of voters that list flag[j] for the
  432. * currently considered router. */
  433. int i;
  434. smartlist_t *matching_descs = smartlist_create();
  435. smartlist_t *chosen_flags = smartlist_create();
  436. smartlist_t *versions = smartlist_create();
  437. int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
  438. * votes[j] knows about. */
  439. int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
  440. * about flags[f]. */
  441. int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
  442. * is the same flag as votes[j]->known_flags[b]. */
  443. int *named_flag; /* Index of the flag "Named" for votes[j] */
  444. index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  445. size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
  446. n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
  447. n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
  448. flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  449. named_flag = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
  450. for (i = 0; i < smartlist_len(votes); ++i)
  451. named_flag[i] = -1;
  452. SMARTLIST_FOREACH(votes, networkstatus_vote_t *, v,
  453. {
  454. flag_map[v_sl_idx] = tor_malloc_zero(
  455. sizeof(int)*smartlist_len(v->known_flags));
  456. SMARTLIST_FOREACH(v->known_flags, const char *, fl,
  457. {
  458. int p = smartlist_string_pos(flags, fl);
  459. tor_assert(p >= 0);
  460. flag_map[v_sl_idx][fl_sl_idx] = p;
  461. ++n_flag_voters[p];
  462. if (!strcmp(fl, "Named"))
  463. named_flag[v_sl_idx] = fl_sl_idx;
  464. });
  465. n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
  466. size[v_sl_idx] = smartlist_len(v->routerstatus_list);
  467. });
  468. /* Now go through all the votes */
  469. flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
  470. while (1) {
  471. vote_routerstatus_t *rs;
  472. routerstatus_t rs_out;
  473. const char *lowest_id = NULL;
  474. const char *chosen_version;
  475. const char *chosen_name = NULL;
  476. int naming_conflict = 0;
  477. int n_listing = 0;
  478. int i;
  479. char buf[256];
  480. /* Of the next-to-be-considered digest in each voter, which is first? */
  481. SMARTLIST_FOREACH(votes, networkstatus_vote_t *, v, {
  482. if (index[v_sl_idx] < size[v_sl_idx]) {
  483. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  484. if (!lowest_id ||
  485. memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN) < 0)
  486. lowest_id = rs->status.identity_digest;
  487. }
  488. });
  489. if (!lowest_id) /* we're out of routers. */
  490. break;
  491. memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
  492. smartlist_clear(matching_descs);
  493. smartlist_clear(chosen_flags);
  494. smartlist_clear(versions);
  495. /* Okay, go through all the entries for this digest. */
  496. SMARTLIST_FOREACH(votes, networkstatus_vote_t *, v, {
  497. if (index[v_sl_idx] >= size[v_sl_idx])
  498. continue; /* out of entries. */
  499. rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
  500. if (memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
  501. continue; /* doesn't include this router. */
  502. /* At this point, we know that we're looking at a routersatus with
  503. * identity "lowest".
  504. */
  505. ++index[v_sl_idx];
  506. ++n_listing;
  507. smartlist_add(matching_descs, rs);
  508. if (rs->version && rs->version[0])
  509. smartlist_add(versions, rs->version);
  510. /* Tally up all the flags. */
  511. for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
  512. if (rs->flags & (U64_LITERAL(1) << i))
  513. ++flag_counts[flag_map[v_sl_idx][i]];
  514. }
  515. if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
  516. if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
  517. log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
  518. chosen_name, rs->status.nickname);
  519. naming_conflict = 1;
  520. }
  521. chosen_name = rs->status.nickname;
  522. }
  523. });
  524. /* We don't include this router at all unless more than half of
  525. * the authorities we believe in list it. */
  526. if (n_listing <= total_authorities/2)
  527. continue;
  528. /* Figure out the most popular opinion of what the most recent
  529. * routerinfo and its contents are. */
  530. rs = compute_routerstatus_consensus(matching_descs);
  531. /* Copy bits of that into rs_out. */
  532. tor_assert(!memcmp(lowest_id, rs->status.identity_digest, DIGEST_LEN));
  533. memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
  534. memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
  535. DIGEST_LEN);
  536. rs_out.addr = rs->status.addr;
  537. rs_out.published_on = rs->status.published_on;
  538. rs_out.dir_port = rs->status.dir_port;
  539. rs_out.or_port = rs->status.or_port;
  540. if (chosen_name && !naming_conflict) {
  541. strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
  542. } else {
  543. strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
  544. }
  545. /* Set the flags. */
  546. smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
  547. SMARTLIST_FOREACH(flags, const char *, fl,
  548. {
  549. if (strcmp(fl, "Named")) {
  550. if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2)
  551. smartlist_add(chosen_flags, (char*)fl);
  552. } else {
  553. if (!naming_conflict && flag_counts[fl_sl_idx])
  554. smartlist_add(chosen_flags, (char*)"Named");
  555. }
  556. });
  557. /* Pick the version. */
  558. if (smartlist_len(versions)) {
  559. sort_version_list(versions, 0);
  560. chosen_version = get_most_frequent_member(versions);
  561. } else {
  562. chosen_version = NULL;
  563. }
  564. /* Okay!! Now we can write the descriptor... */
  565. /* First line goes into "buf". */
  566. routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL, 1);
  567. smartlist_add(chunks, tor_strdup(buf));
  568. /* Second line is all flags. The "\n" is missing. */
  569. smartlist_add(chunks,
  570. smartlist_join_strings(chosen_flags, " ", 0, NULL));
  571. /* Now the version line. */
  572. if (chosen_version) {
  573. smartlist_add(chunks, tor_strdup("\nv "));
  574. smartlist_add(chunks, tor_strdup(chosen_version));
  575. }
  576. smartlist_add(chunks, tor_strdup("\n"));
  577. /* And the loop is over and we move on to the next router */
  578. }
  579. tor_free(index);
  580. tor_free(size);
  581. tor_free(n_voter_flags);
  582. tor_free(n_flag_voters);
  583. for (i = 0; i < smartlist_len(votes); ++i)
  584. tor_free(flag_map[i]);
  585. tor_free(flag_map);
  586. tor_free(flag_counts);
  587. smartlist_free(matching_descs);
  588. smartlist_free(chosen_flags);
  589. smartlist_free(versions);
  590. }
  591. /* Add a signature. */
  592. {
  593. char digest[DIGEST_LEN];
  594. char fingerprint[HEX_DIGEST_LEN+1];
  595. char signing_key_fingerprint[HEX_DIGEST_LEN+1];
  596. char buf[4096];
  597. smartlist_add(chunks, tor_strdup("directory-signature "));
  598. /* Compute the hash of the chunks. */
  599. hash_list_members(digest, chunks);
  600. /* Get the fingerprints */
  601. crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
  602. crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
  603. /* add the junk that will go at the end of the line. */
  604. tor_snprintf(buf, sizeof(buf), "%s %s\n", fingerprint,
  605. signing_key_fingerprint);
  606. /* And the signature. */
  607. if (router_append_dirobj_signature(buf, sizeof(buf), digest,
  608. signing_key)) {
  609. log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
  610. return NULL; /* This leaks, but it should never happen. */
  611. }
  612. smartlist_add(chunks, tor_strdup(buf));
  613. }
  614. result = smartlist_join_strings(chunks, "", 0, NULL);
  615. tor_free(client_versions);
  616. tor_free(server_versions);
  617. smartlist_free(flags);
  618. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  619. smartlist_free(chunks);
  620. {
  621. networkstatus_vote_t *c;
  622. if (!(c = networkstatus_parse_vote_from_string(result, 0))) {
  623. log_err(LD_BUG,"Generated a networkstatus consensus we couldn't "
  624. "parse.");
  625. tor_free(result);
  626. return NULL;
  627. }
  628. networkstatus_vote_free(c);
  629. }
  630. return result;
  631. }
  632. /** Check whether the signature on <b>voter</b> is correctly signed by
  633. * the signing key of <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
  634. * signing key; otherwise set the good_signature or bad_signature flag on
  635. * <b>voter</b>, and return 0. */
  636. /* (private; exposed for testing.) */
  637. int
  638. networkstatus_check_voter_signature(networkstatus_vote_t *consensus,
  639. networkstatus_voter_info_t *voter,
  640. authority_cert_t *cert)
  641. {
  642. char d[DIGEST_LEN];
  643. char *signed_digest;
  644. size_t signed_digest_len;
  645. if (crypto_pk_get_digest(cert->signing_key, d)<0)
  646. return -1;
  647. if (memcmp(voter->signing_key_digest, d, DIGEST_LEN))
  648. return -1;
  649. signed_digest_len = crypto_pk_keysize(cert->signing_key);
  650. signed_digest = tor_malloc(signed_digest_len);
  651. if (crypto_pk_public_checksig(cert->signing_key,
  652. signed_digest,
  653. voter->signature,
  654. voter->signature_len) != DIGEST_LEN ||
  655. memcmp(signed_digest, consensus->networkstatus_digest, DIGEST_LEN)) {
  656. log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
  657. voter->bad_signature = 1;
  658. } else {
  659. voter->good_signature = 1;
  660. }
  661. return 0;
  662. }
  663. /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
  664. * as-yet-unchecked signature on <b>consensus. Return 0 if there are enough
  665. * good signatures from recognized authorities on it, and -1 otherwise. */
  666. int
  667. networkstatus_check_consensus_signature(networkstatus_vote_t *consensus)
  668. {
  669. int n_good = 0;
  670. int n_missing_key = 0;
  671. int n_bad = 0;
  672. int n_unknown = 0;
  673. int n_no_signature = 0;
  674. int n_required = get_n_authorities(V3_AUTHORITY)/2 + 1;
  675. tor_assert(! consensus->is_vote);
  676. SMARTLIST_FOREACH(consensus->voters, networkstatus_voter_info_t *, voter,
  677. {
  678. if (!voter->good_signature && !voter->bad_signature && voter->signature) {
  679. /* we can try to check the signature. */
  680. authority_cert_t *cert =
  681. authority_cert_get_by_digests(voter->identity_digest,
  682. voter->signing_key_digest);
  683. if (! cert) {
  684. ++n_unknown;
  685. continue;
  686. }
  687. if (networkstatus_check_voter_signature(consensus, voter, cert) < 0) {
  688. ++n_missing_key;
  689. continue;
  690. }
  691. }
  692. if (voter->good_signature)
  693. ++n_good;
  694. else if (voter->bad_signature)
  695. ++n_bad;
  696. else
  697. ++n_no_signature;
  698. });
  699. log_notice(LD_DIR,
  700. "%d unknown, %d missing key, %d good, %d bad, %d no signature, "
  701. "%d required", n_unknown, n_missing_key, n_good, n_bad,
  702. n_no_signature, n_required);
  703. if (n_good >= n_required)
  704. return 0;
  705. else
  706. return -1;
  707. }
  708. /** Given a consensus vote <b>target</b> and a list of
  709. * notworkstatus_voter_info_t in <b>src_voter_list</b> that correspond to the
  710. * same consensus, check whether there are any new signatures in
  711. * <b>src_voter_list</b> that should be added to <b>target. (A signature
  712. * should be added if we have no signature for that voter in <b>target</b>
  713. * yet, or if we have no verifiable signature and the new signature is
  714. * verifiable.) Set *<b>new_signatures_out</b> to a newly allocated string
  715. * holding the newly added signatures; set *<b>regenerate_out</b> to true if
  716. * we replaced a signature and 0 otherwise. Return the number of signatures
  717. * added or changed. */
  718. static int
  719. networkstatus_add_signatures_impl(networkstatus_vote_t *target,
  720. smartlist_t *src_voter_list,
  721. char **new_signatures_out,
  722. int *regenerate_out)
  723. {
  724. smartlist_t *added_signatures, *sigs;
  725. int r;
  726. tor_assert(target);
  727. tor_assert(!target->is_vote);
  728. tor_assert(new_signatures_out);
  729. tor_assert(regenerate_out);
  730. added_signatures = smartlist_create();
  731. /* For each voter in src... */
  732. SMARTLIST_FOREACH(src_voter_list, networkstatus_voter_info_t *, src_voter,
  733. {
  734. networkstatus_voter_info_t *target_voter =
  735. networkstatus_get_voter_by_id(target, src_voter->identity_digest);
  736. authority_cert_t *cert;
  737. /* If the target a doesn't know about this voter, then forget it. */
  738. if (!target_voter)
  739. continue;
  740. /* If the target already has a good signature from this voter, then skip
  741. * this one. */
  742. if (target_voter->good_signature)
  743. continue;
  744. /* Try checking the signature if we haven't already. */
  745. if (!src_voter->good_signature && !src_voter->bad_signature) {
  746. cert = authority_cert_get_by_digests(src_voter->identity_digest,
  747. src_voter->signing_key_digest);
  748. if (cert) {
  749. networkstatus_check_voter_signature(target, src_voter, cert);
  750. }
  751. }
  752. /* If this signature is good, or we don't have ay signature yet,
  753. * then add it. */
  754. if (src_voter->good_signature || !target_voter->signature) {
  755. if (target_voter->signature)
  756. *regenerate_out = 1;
  757. tor_free(target_voter->signature);
  758. target_voter->signature =
  759. tor_memdup(src_voter->signature, src_voter->signature_len);
  760. memcpy(target_voter->signing_key_digest, src_voter->signing_key_digest,
  761. DIGEST_LEN);
  762. target_voter->signature_len = src_voter->signature_len;
  763. target_voter->good_signature = 1;
  764. target_voter->bad_signature = 0;
  765. smartlist_add(added_signatures, target_voter);
  766. }
  767. });
  768. sigs = smartlist_create();
  769. SMARTLIST_FOREACH(added_signatures, networkstatus_voter_info_t *, v,
  770. {
  771. char buf[4096];
  772. char sk[HEX_DIGEST_LEN+1];
  773. char ik[HEX_DIGEST_LEN+1];
  774. tor_assert(v->signature);
  775. base16_encode(sk, sizeof(sk), v->signing_key_digest, DIGEST_LEN);
  776. base16_encode(ik, sizeof(ik), v->identity_digest, DIGEST_LEN);
  777. tor_snprintf(buf, sizeof(buf), "directory-signature %s %s\n"
  778. "-----BEGIN SIGNATURE-----\n", ik, sk);
  779. smartlist_add(sigs, tor_strdup(buf));
  780. base64_encode(buf, sizeof(buf), v->signature, v->signature_len);
  781. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  782. smartlist_add(sigs, tor_strdup(buf));
  783. });
  784. *new_signatures_out = smartlist_join_strings(sigs, "", 0, NULL);
  785. SMARTLIST_FOREACH(sigs, char *, cp, tor_free(cp));
  786. smartlist_free(sigs);
  787. r = smartlist_len(added_signatures);
  788. smartlist_free(added_signatures);
  789. return r;
  790. }
  791. /** As networkstatus_add_consensus_signature_impl, but takes new signatures
  792. * from the consensus in <b>src</b>. */
  793. int
  794. networkstatus_add_consensus_signatures(networkstatus_vote_t *target,
  795. networkstatus_vote_t *src,
  796. char **new_signatures_out,
  797. int *regenerate_out)
  798. {
  799. tor_assert(src);
  800. tor_assert(! src->is_vote);
  801. *new_signatures_out = NULL;
  802. /* Are they the same consensus? */
  803. if (memcmp(target->networkstatus_digest, src->networkstatus_digest,
  804. DIGEST_LEN))
  805. return -1;
  806. if (target == src)
  807. return 0;
  808. return networkstatus_add_signatures_impl(target, src->voters,
  809. new_signatures_out,
  810. regenerate_out);
  811. }
  812. /** As networkstatus_add_consensus_signature_impl, but takes new signatures
  813. * from the detached signatures document <b>sigs</b>. */
  814. int
  815. networkstatus_add_detached_signatures(networkstatus_vote_t *target,
  816. ns_detached_signatures_t *sigs,
  817. char **new_signatures_out,
  818. int *regenerate_out)
  819. {
  820. tor_assert(sigs);
  821. *new_signatures_out = NULL;
  822. /* Are they the same consensus? */
  823. if (memcmp(target->networkstatus_digest, sigs->networkstatus_digest,
  824. DIGEST_LEN))
  825. return -1;
  826. return networkstatus_add_signatures_impl(target, sigs->signatures,
  827. new_signatures_out,
  828. regenerate_out);
  829. }
  830. /** Return a newly allocated string holding the detached-signatures document
  831. * corresponding to the signatures on <b>consensus</b>. */
  832. char *
  833. networkstatus_get_detached_signatures(networkstatus_vote_t *consensus)
  834. {
  835. smartlist_t *elements;
  836. char buf[4096];
  837. char *result = NULL;
  838. int n_sigs = 0;
  839. tor_assert(consensus);
  840. tor_assert(! consensus->is_vote);
  841. elements = smartlist_create();
  842. {
  843. char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
  844. vu_buf[ISO_TIME_LEN+1];
  845. char d[HEX_DIGEST_LEN+1];
  846. base16_encode(d, sizeof(d), consensus->networkstatus_digest, DIGEST_LEN);
  847. format_iso_time(va_buf, consensus->valid_after);
  848. format_iso_time(fu_buf, consensus->fresh_until);
  849. format_iso_time(vu_buf, consensus->valid_until);
  850. tor_snprintf(buf, sizeof(buf),
  851. "consensus-digest %s\n"
  852. "valid-after %s\n"
  853. "fresh-until %s\n"
  854. "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
  855. smartlist_add(elements, tor_strdup(buf));
  856. }
  857. SMARTLIST_FOREACH(consensus->voters, networkstatus_voter_info_t *, v,
  858. {
  859. char sk[HEX_DIGEST_LEN+1];
  860. char id[HEX_DIGEST_LEN+1];
  861. if (!v->signature || v->bad_signature)
  862. continue;
  863. ++n_sigs;
  864. base16_encode(sk, sizeof(sk), v->signing_key_digest, DIGEST_LEN);
  865. base16_encode(id, sizeof(id), v->identity_digest, DIGEST_LEN);
  866. tor_snprintf(buf, sizeof(buf),
  867. "directory-signature %s %s\n-----BEGIN SIGNATURE-----\n",
  868. id, sk);
  869. smartlist_add(elements, tor_strdup(buf));
  870. base64_encode(buf, sizeof(buf), v->signature, v->signature_len);
  871. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  872. smartlist_add(elements, tor_strdup(buf));
  873. });
  874. result = smartlist_join_strings(elements, "", 0, NULL);
  875. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  876. smartlist_free(elements);
  877. if (!n_sigs)
  878. tor_free(result);
  879. return result;
  880. }
  881. /** Release all storage held in <b>s</b>. */
  882. void
  883. ns_detached_signatures_free(ns_detached_signatures_t *s)
  884. {
  885. if (s->signatures) {
  886. SMARTLIST_FOREACH(s->signatures, networkstatus_voter_info_t *, v,
  887. {
  888. tor_free(v->signature);
  889. tor_free(v);
  890. });
  891. smartlist_free(s->signatures);
  892. }
  893. tor_free(s);
  894. }
  895. /* =====
  896. * Certificate functions
  897. * ===== */
  898. /** Free storage held in <b>cert</b>. */
  899. void
  900. authority_cert_free(authority_cert_t *cert)
  901. {
  902. if (!cert)
  903. return;
  904. tor_free(cert->cache_info.signed_descriptor_body);
  905. if (cert->signing_key)
  906. crypto_free_pk_env(cert->signing_key);
  907. if (cert->identity_key)
  908. crypto_free_pk_env(cert->identity_key);
  909. tor_free(cert);
  910. }
  911. /** Allocate and return a new authority_cert_t with the same contents as
  912. * <b>cert</b>. */
  913. authority_cert_t *
  914. authority_cert_dup(authority_cert_t *cert)
  915. {
  916. authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
  917. tor_assert(cert);
  918. memcpy(out, cert, sizeof(authority_cert_t));
  919. /* Now copy pointed-to things. */
  920. out->cache_info.signed_descriptor_body =
  921. tor_strndup(cert->cache_info.signed_descriptor_body,
  922. cert->cache_info.signed_descriptor_len);
  923. out->cache_info.saved_location = SAVED_NOWHERE;
  924. out->identity_key = crypto_pk_dup_key(cert->identity_key);
  925. out->signing_key = crypto_pk_dup_key(cert->signing_key);
  926. return out;
  927. }
  928. /* =====
  929. * Vote scheduling
  930. * ===== */
  931. /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
  932. * Note that these aren't the intervals we'll use to vote; they're the ones
  933. * that we'll vote to use. */
  934. void
  935. dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
  936. {
  937. or_options_t *options = get_options();
  938. tor_assert(timing_out);
  939. timing_out->vote_interval = options->V3AuthVotingInterval;
  940. timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
  941. timing_out->vote_delay = options->V3AuthVoteDelay;
  942. timing_out->dist_delay = options->V3AuthDistDelay;
  943. }
  944. /** Return the start of the next interval of size <b>interval</b> (in seconds)
  945. * after <b>now</b>. Midnight always starts a fresh interval, and if the last
  946. * interval of a day would be truncated to less than half its size, it is
  947. * rolled into the previous interval. */
  948. time_t
  949. dirvote_get_start_of_next_interval(time_t now, int interval)
  950. {
  951. struct tm tm;
  952. time_t midnight_today;
  953. time_t midnight_tomorrow;
  954. time_t next;
  955. tor_gmtime_r(&now, &tm);
  956. tm.tm_hour = 0;
  957. tm.tm_min = 0;
  958. tm.tm_sec = 0;
  959. midnight_today = tor_timegm(&tm);
  960. midnight_tomorrow = midnight_today + (24*60*60);
  961. next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
  962. /* Intervals never cross midnight. */
  963. if (next > midnight_tomorrow)
  964. next = midnight_tomorrow;
  965. /* If the interval would only last half as long as it's supposed to, then
  966. * skip over to the next day. */
  967. if (next + interval/2 > midnight_tomorrow)
  968. next = midnight_tomorrow;
  969. return next;
  970. }
  971. /** Scheduling information for a voting interval. */
  972. static struct {
  973. /** When do we generate and distribute our vote for this interval? */
  974. time_t voting_starts;
  975. /** When do we give up on getting more votes and generate a consensus? */
  976. time_t voting_ends;
  977. /** When do we publish the consensus? */
  978. time_t interval_starts;
  979. /** When do we discard old votes and pending detached signatures? */
  980. time_t discard_old_votes;
  981. /* True iff we have generated and distributed our vote. */
  982. int have_voted;
  983. /* True iff we have built a consensus and sent the signatures around. */
  984. int have_built_consensus;
  985. /* True iff we have published our consensus. */
  986. int have_published_consensus;
  987. } voting_schedule = {0,0,0,0,0,0,0};
  988. /** Set voting_schedule to hold the timing for the next vote we should be
  989. * doing. */
  990. void
  991. dirvote_recalculate_timing(time_t now)
  992. {
  993. /* XXXX020 call this when inputs may have changed (i.e., whenver we get a
  994. * fresh consensus.) */
  995. int interval, vote_delay, dist_delay;
  996. time_t start;
  997. time_t end;
  998. networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
  999. memset(&voting_schedule, 0, sizeof(voting_schedule));
  1000. if (consensus) {
  1001. interval = consensus->fresh_until - consensus->valid_after;
  1002. vote_delay = consensus->vote_seconds;
  1003. dist_delay = consensus->dist_seconds;
  1004. } else {
  1005. interval = 30*60;
  1006. vote_delay = dist_delay = 300;
  1007. }
  1008. tor_assert(interval > 0);
  1009. if (vote_delay + dist_delay > interval/2)
  1010. vote_delay = dist_delay = interval / 4;
  1011. start = voting_schedule.interval_starts =
  1012. dirvote_get_start_of_next_interval(now,interval);
  1013. end = dirvote_get_start_of_next_interval(start+1, interval);
  1014. tor_assert(end > start);
  1015. voting_schedule.voting_ends = start - vote_delay;
  1016. voting_schedule.voting_starts = start - vote_delay - dist_delay;
  1017. voting_schedule.discard_old_votes = start +
  1018. ((end-start) - vote_delay - dist_delay)/2 ;
  1019. }
  1020. /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
  1021. void
  1022. dirvote_act(time_t now)
  1023. {
  1024. if (!voting_schedule.voting_starts) {
  1025. char *keys = list_v3_auth_ids();
  1026. authority_cert_t *c = get_my_v3_authority_cert();
  1027. log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s."
  1028. "Mine is %s.",
  1029. keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
  1030. tor_free(keys);
  1031. dirvote_recalculate_timing(now);
  1032. }
  1033. if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
  1034. log_notice(LD_DIR, "Time to vote.");
  1035. dirvote_perform_vote();
  1036. voting_schedule.have_voted = 1;
  1037. }
  1038. /* XXXX020 after a couple minutes here, start trying to fetch votes. */
  1039. if (voting_schedule.voting_ends < now &&
  1040. !voting_schedule.have_built_consensus) {
  1041. log_notice(LD_DIR, "Time to compute a consensus.");
  1042. dirvote_compute_consensus();
  1043. /* XXXX020 we will want to try again later if we haven't got enough
  1044. * votes yet. */
  1045. voting_schedule.have_built_consensus = 1;
  1046. }
  1047. if (voting_schedule.interval_starts < now &&
  1048. !voting_schedule.have_published_consensus) {
  1049. log_notice(LD_DIR, "Time to publish the consensus.");
  1050. dirvote_publish_consensus();
  1051. /* XXXX020 we will want to try again later if we haven't got enough
  1052. * signatures yet. */
  1053. voting_schedule.have_published_consensus = 1;
  1054. }
  1055. if (voting_schedule.discard_old_votes < now) {
  1056. log_notice(LD_DIR, "Time to discard old votes.");
  1057. dirvote_clear_pending_votes();
  1058. dirvote_recalculate_timing(now);
  1059. }
  1060. }
  1061. /** A vote networkstatus_vote_t and its unparsed body: held around so we can
  1062. * use it to generate a consensus (at voting_ends) and so we can serve it to
  1063. * other authorities that might want it. */
  1064. typedef struct pending_vote_t {
  1065. cached_dir_t *vote_body;
  1066. networkstatus_vote_t *vote;
  1067. } pending_vote_t;
  1068. /** List of pending_vote_t for the current vote. */
  1069. static smartlist_t *pending_vote_list = NULL;
  1070. /** The body of the consensus that we're currently building. Once we
  1071. * have it built, it goes into dirserv.c */
  1072. static char *pending_consensus_body = NULL;
  1073. /** The detached signatures for the consensus that we're currently
  1074. * building. */
  1075. static char *pending_consensus_signatures = NULL;
  1076. /** The parsed in-progress consensus document. */
  1077. static networkstatus_vote_t *pending_consensus = NULL;
  1078. /** List of ns_detached_signatures_t: hold signatures that get posted to us
  1079. * before we have generated the consensus on our own. */
  1080. static smartlist_t *pending_consensus_signature_list = NULL;
  1081. /** Generate a networkstatus vote and post it to all the v3 authorities.
  1082. * (V3 Authority only) */
  1083. void
  1084. dirvote_perform_vote(void)
  1085. {
  1086. cached_dir_t *new_vote = generate_v3_networkstatus();
  1087. pending_vote_t *pending_vote;
  1088. int status;
  1089. const char *msg = "";
  1090. if (!new_vote)
  1091. return;
  1092. if (!(pending_vote = dirvote_add_vote(new_vote->dir, &msg, &status))) {
  1093. log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
  1094. msg);
  1095. return;
  1096. }
  1097. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
  1098. ROUTER_PURPOSE_GENERAL,
  1099. V3_AUTHORITY,
  1100. pending_vote->vote_body->dir,
  1101. pending_vote->vote_body->dir_len, 0);
  1102. log_notice(LD_DIR, "Vote posted.");
  1103. }
  1104. /** Drop all currently pending votes, consensus, and detached signatures. */
  1105. void
  1106. dirvote_clear_pending_votes(void)
  1107. {
  1108. if (pending_vote_list) {
  1109. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1110. cached_dir_decref(v->vote_body);
  1111. v->vote_body = NULL;
  1112. networkstatus_vote_free(v->vote);
  1113. tor_free(v);
  1114. });
  1115. smartlist_clear(pending_vote_list);
  1116. }
  1117. if (pending_consensus_signature_list) {
  1118. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
  1119. tor_free(cp));
  1120. smartlist_clear(pending_consensus_signature_list);
  1121. }
  1122. tor_free(pending_consensus_body);
  1123. tor_free(pending_consensus_signatures);
  1124. if (pending_consensus) {
  1125. networkstatus_vote_free(pending_consensus);
  1126. pending_consensus = NULL;
  1127. }
  1128. }
  1129. /* XXXX020 delete me. */
  1130. static char *
  1131. list_v3_auth_ids(void)
  1132. {
  1133. smartlist_t *known_v3_keys = smartlist_create();
  1134. char *keys;
  1135. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1136. trusted_dir_server_t *, ds,
  1137. if (!tor_digest_is_zero(ds->v3_identity_digest))
  1138. smartlist_add(known_v3_keys,
  1139. tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
  1140. keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
  1141. SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
  1142. smartlist_free(known_v3_keys);
  1143. return keys;
  1144. }
  1145. /** Called when we have received a networkstatus vote in <b>vote_body</b>.
  1146. * Parse and validate it, and on success store it as a pending vote (which we
  1147. * then return). Return NULL on failure. Sets *<b>msg_out</b> and
  1148. * *<b>status_out</b> to an HTTP response and status code. (V3 authority
  1149. * only) */
  1150. pending_vote_t *
  1151. dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
  1152. {
  1153. networkstatus_vote_t *vote;
  1154. networkstatus_voter_info_t *vi;
  1155. trusted_dir_server_t *ds;
  1156. pending_vote_t *pending_vote = NULL;
  1157. tor_assert(vote_body);
  1158. tor_assert(msg_out);
  1159. tor_assert(status_out);
  1160. *status_out = 0;
  1161. if (!pending_vote_list)
  1162. pending_vote_list = smartlist_create();
  1163. *msg_out = NULL;
  1164. vote = networkstatus_parse_vote_from_string(vote_body, 1);
  1165. if (!vote) {
  1166. *msg_out = "Unable to parse vote";
  1167. goto err;
  1168. }
  1169. tor_assert(smartlist_len(vote->voters) == 1);
  1170. vi = get_voter(vote);
  1171. tor_assert(vi->good_signature == 1);
  1172. ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
  1173. if (!ds || !(ds->type & V3_AUTHORITY)) {
  1174. char *keys = list_v3_auth_ids();
  1175. log_warn(LD_DIR, "Got a vote from an authority with authority key ID %s. "
  1176. "This authority %s. Known v3 key IDs are: %s",
  1177. hex_str(vi->identity_digest, DIGEST_LEN),
  1178. ds?"is not recognized":"is recognized, but is not listed as v3",
  1179. keys);
  1180. tor_free(keys);
  1181. *msg_out = "Vote not from a recognized v3 authority";
  1182. goto err;
  1183. }
  1184. tor_assert(vote->cert);
  1185. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1186. vote->cert->signing_key_digest)) {
  1187. /* Hey, it's a new cert! */
  1188. trusted_dirs_load_certs_from_string(
  1189. vote->cert->cache_info.signed_descriptor_body,
  1190. 0 /* from_store */);
  1191. if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
  1192. vote->cert->signing_key_digest)) {
  1193. log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
  1194. }
  1195. }
  1196. /* Is it for the right period? */
  1197. if (vote->valid_after != voting_schedule.interval_starts) {
  1198. char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
  1199. format_iso_time(tbuf1, vote->valid_after);
  1200. format_iso_time(tbuf2, voting_schedule.interval_starts);
  1201. log_warn(LD_DIR, "Rejecting vote with valid-after time of %s; we were "
  1202. "expecting %s", tbuf1, tbuf2);
  1203. *msg_out = "Bad valid-after time";
  1204. goto err;
  1205. }
  1206. /* Now see whether we already have a vote from this authority.*/
  1207. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
  1208. if (! memcmp(v->vote->cert->cache_info.identity_digest,
  1209. vote->cert->cache_info.identity_digest,
  1210. DIGEST_LEN)) {
  1211. networkstatus_voter_info_t *vi_old = get_voter(v->vote);
  1212. if (!memcmp(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
  1213. /* Ah, it's the same vote. Not a problem. */
  1214. log_info(LD_DIR, "Discarding a vote we already have.");
  1215. *status_out = 200;
  1216. *msg_out = "ok";
  1217. goto err;
  1218. } else if (v->vote->published < vote->published) {
  1219. log_notice(LD_DIR, "Replacing an older pending vote from this "
  1220. "directory.");
  1221. cached_dir_decref(v->vote_body);
  1222. networkstatus_vote_free(v->vote);
  1223. v->vote_body = new_cached_dir(tor_strdup(vote_body),
  1224. vote->published);
  1225. v->vote = vote;
  1226. *msg_out = "ok";
  1227. return v;
  1228. } else {
  1229. *msg_out = "Already have a newer pending vote";
  1230. goto err;
  1231. }
  1232. }
  1233. });
  1234. pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
  1235. pending_vote->vote_body = new_cached_dir(tor_strdup(vote_body),
  1236. vote->published);
  1237. pending_vote->vote = vote;
  1238. smartlist_add(pending_vote_list, pending_vote);
  1239. if (!*status_out)
  1240. *status_out = 200;
  1241. *msg_out = "ok";
  1242. return pending_vote;
  1243. err:
  1244. if (vote)
  1245. networkstatus_vote_free(vote);
  1246. if (!*msg_out)
  1247. *msg_out = "Error adding vote";
  1248. if (!*status_out)
  1249. *status_out = 400;
  1250. return NULL;
  1251. }
  1252. /** Try to compute a v3 networkstatus consensus from the currently pending
  1253. * votes. Return 0 on success, -1 on failure. Store the consensus in
  1254. * pending_consensus: it won't be ready to be published until we have
  1255. * everybody else's signatures collected too. (V3 Authoritity only) */
  1256. int
  1257. dirvote_compute_consensus(void)
  1258. {
  1259. /* Have we got enough votes to try? */
  1260. int n_votes, n_voters;
  1261. smartlist_t *votes = NULL;
  1262. char *consensus_body = NULL, *signatures = NULL;
  1263. networkstatus_vote_t *consensus = NULL;
  1264. authority_cert_t *my_cert;
  1265. if (!pending_vote_list)
  1266. pending_vote_list = smartlist_create();
  1267. n_voters = get_n_authorities(V3_AUTHORITY);
  1268. n_votes = smartlist_len(pending_vote_list);
  1269. if (n_votes <= n_voters/2) {
  1270. log_warn(LD_DIR, "We don't have enough votes to generate a consensus.");
  1271. goto err;
  1272. }
  1273. if (!(my_cert = get_my_v3_authority_cert())) {
  1274. log_warn(LD_DIR, "Can't generate consensus without a certificate.");
  1275. goto err;
  1276. }
  1277. votes = smartlist_create();
  1278. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
  1279. smartlist_add(votes, v->vote));
  1280. consensus_body = networkstatus_compute_consensus(
  1281. votes, n_voters,
  1282. my_cert->identity_key,
  1283. get_my_v3_authority_signing_key());
  1284. if (!consensus_body) {
  1285. log_warn(LD_DIR, "Couldn't generate a consensus at all!");
  1286. goto err;
  1287. }
  1288. consensus = networkstatus_parse_vote_from_string(consensus_body, 0);
  1289. if (!consensus) {
  1290. log_warn(LD_DIR, "Couldn't parse consensus we generated!");
  1291. goto err;
  1292. }
  1293. /* 'Check' our own signature, to mark it valid. */
  1294. networkstatus_check_consensus_signature(consensus);
  1295. signatures = networkstatus_get_detached_signatures(consensus);
  1296. if (!signatures) {
  1297. log_warn(LD_DIR, "Couldn't extract signatures.");
  1298. goto err;
  1299. }
  1300. tor_free(pending_consensus_body);
  1301. pending_consensus_body = consensus_body;
  1302. tor_free(pending_consensus_signatures);
  1303. pending_consensus_signatures = signatures;
  1304. if (pending_consensus)
  1305. networkstatus_vote_free(pending_consensus);
  1306. pending_consensus = consensus;
  1307. if (pending_consensus_signature_list) {
  1308. int n_sigs = 0;
  1309. /* we may have gotten signatures for this consensus before we built
  1310. * it ourself. Add them now. */
  1311. SMARTLIST_FOREACH(pending_consensus_signature_list, char *, sig,
  1312. {
  1313. const char *msg = NULL;
  1314. n_sigs += dirvote_add_signatures_to_pending_consensus(sig, &msg);
  1315. tor_free(sig);
  1316. });
  1317. if (n_sigs)
  1318. log_notice(LD_DIR, "Added %d pending signatures while building "
  1319. "consensus.", n_sigs);
  1320. smartlist_clear(pending_consensus_signature_list);
  1321. }
  1322. log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
  1323. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
  1324. ROUTER_PURPOSE_GENERAL,
  1325. V3_AUTHORITY,
  1326. pending_consensus_signatures,
  1327. strlen(pending_consensus_signatures), 0);
  1328. log_notice(LD_DIR, "Signature(s) posted.");
  1329. return 0;
  1330. err:
  1331. if (votes)
  1332. smartlist_free(votes);
  1333. tor_free(consensus_body);
  1334. tor_free(signatures);
  1335. networkstatus_vote_free(consensus);
  1336. return -1;
  1337. }
  1338. /** Helper: we just got the <b>deteached_signatures_body</b> sent to us as
  1339. * signatures on the currently pending consensus. Add them to the consensus
  1340. * as appropriate. Return the number of signatures added. (?) */
  1341. static int
  1342. dirvote_add_signatures_to_pending_consensus(
  1343. const char *detached_signatures_body,
  1344. const char **msg_out)
  1345. {
  1346. ns_detached_signatures_t *sigs = NULL;
  1347. int r = -1, regenerate=0;
  1348. char *new_signatures = NULL;
  1349. size_t siglen;
  1350. tor_assert(detached_signatures_body);
  1351. tor_assert(msg_out);
  1352. /* Only call if we have a pending consensus right now. */
  1353. tor_assert(pending_consensus);
  1354. tor_assert(pending_consensus_body);
  1355. tor_assert(pending_consensus_signatures);
  1356. *msg_out = NULL;
  1357. if (!(sigs = networkstatus_parse_detached_signatures(
  1358. detached_signatures_body, NULL))) {
  1359. *msg_out = "Couldn't parse detached signatures.";
  1360. goto err;
  1361. }
  1362. r = networkstatus_add_detached_signatures(pending_consensus,
  1363. sigs,
  1364. &new_signatures,
  1365. &regenerate);
  1366. // XXXX020 originally, this test was regenerate && r >= 0). But one
  1367. // code path is simpler than 2.
  1368. if (new_signatures && (siglen = strlen(new_signatures)) && r >= 0) {
  1369. /* XXXX This should really be its own function. */
  1370. char *new_detached =
  1371. networkstatus_get_detached_signatures(pending_consensus);
  1372. const char *src;
  1373. char *dst;
  1374. size_t new_consensus_len =
  1375. strlen(pending_consensus_body) + strlen(new_detached) + 1;
  1376. pending_consensus_body = tor_realloc(pending_consensus_body,
  1377. new_consensus_len);
  1378. dst = strstr(pending_consensus_body, "directory-signature ");
  1379. tor_assert(dst);
  1380. src = strstr(new_detached, "directory-signature ");
  1381. tor_assert(src);
  1382. strlcpy(dst, src, new_consensus_len - (dst-pending_consensus_body));
  1383. /* XXXX020 remove this once it fails to crash. */
  1384. {
  1385. ns_detached_signatures_t *sigs =
  1386. networkstatus_parse_detached_signatures(new_detached, NULL);
  1387. networkstatus_vote_t *v = networkstatus_parse_vote_from_string(
  1388. pending_consensus_body, 0);
  1389. tor_assert(sigs);
  1390. ns_detached_signatures_free(sigs);
  1391. tor_assert(v);
  1392. networkstatus_vote_free(v);
  1393. }
  1394. tor_free(pending_consensus_signatures);
  1395. pending_consensus_signatures = new_detached;
  1396. }
  1397. #if 0
  1398. else if (new_signatures && (siglen = strlen(new_signatures)) && r >= 0) {
  1399. size_t siglen = strlen(new_signatures);
  1400. size_t len = strlen(pending_consensus_body);
  1401. pending_consensus_body = tor_realloc(pending_consensus_body,
  1402. len+siglen+1);
  1403. memcpy(pending_consensus_body+len, new_signatures, siglen+1);
  1404. len = strlen(pending_consensus_signatures);
  1405. pending_consensus_signatures = tor_realloc(pending_consensus_signatures,
  1406. len+siglen+1);
  1407. memcpy(pending_consensus_signatures+len, new_signatures, siglen+1);
  1408. log_info(LD_DIR, "Added %d new signatures to the pending consensus.", r);
  1409. }
  1410. #endif
  1411. *msg_out = "ok";
  1412. goto done;
  1413. err:
  1414. if (!msg_out)
  1415. *msg_out = "Unrecognized error while adding detached signatures.";
  1416. done:
  1417. tor_free(new_signatures);
  1418. if (sigs)
  1419. ns_detached_signatures_free(sigs);
  1420. return r;
  1421. }
  1422. /** Helper: we just got the <b>deteached_signatures_body</b> sent to us as
  1423. * signatures on the currently pending consensus. Add them to the pending
  1424. * consensus (if we have one); otherwise queue them until we have a
  1425. * consensus. */
  1426. int
  1427. dirvote_add_signatures(const char *detached_signatures_body)
  1428. {
  1429. /*XXXX020 return value is senseless. */
  1430. if (pending_consensus) {
  1431. const char *msg=NULL;
  1432. log_notice(LD_DIR, "Got a signature. Adding it to the pending consensus.");
  1433. return dirvote_add_signatures_to_pending_consensus(
  1434. detached_signatures_body, &msg);
  1435. } else {
  1436. log_notice(LD_DIR, "Got a signature. Queueing it for the next consensus.");
  1437. if (!pending_consensus_signature_list)
  1438. pending_consensus_signature_list = smartlist_create();
  1439. smartlist_add(pending_consensus_signature_list,
  1440. tor_strdup(detached_signatures_body));
  1441. return 0;
  1442. }
  1443. }
  1444. /** Replace the consensus that we're currently serving with the one that we've
  1445. * been building. (V3 Authority only) */
  1446. int
  1447. dirvote_publish_consensus(void)
  1448. {
  1449. /* Can we actually publish it yet? */
  1450. if (!pending_consensus ||
  1451. networkstatus_check_consensus_signature(pending_consensus)<0) {
  1452. log_warn(LD_DIR, "Not enough info to publish pending consensus");
  1453. return -1;
  1454. }
  1455. if (networkstatus_set_current_consensus(pending_consensus_body, 0))
  1456. log_warn(LD_DIR, "Error publishing consensus");
  1457. else
  1458. log_warn(LD_DIR, "Consensus published.");
  1459. return 0;
  1460. }
  1461. /** Release all static storage held in dirvote.c */
  1462. void
  1463. dirvote_free_all(void)
  1464. {
  1465. dirvote_clear_pending_votes();
  1466. if (pending_vote_list) {
  1467. /* now empty as a result of clear_pending_votes. */
  1468. smartlist_free(pending_vote_list);
  1469. pending_vote_list = NULL;
  1470. }
  1471. tor_free(pending_consensus_body);
  1472. tor_free(pending_consensus_signatures);
  1473. if (pending_consensus) {
  1474. networkstatus_vote_free(pending_consensus);
  1475. pending_consensus = NULL;
  1476. }
  1477. if (pending_consensus_signature_list) {
  1478. /* now empty as a result of clear_pending_votes. */
  1479. smartlist_free(pending_consensus_signature_list);
  1480. pending_consensus_signature_list = NULL;
  1481. }
  1482. }
  1483. /* ====
  1484. * Access to pending items.
  1485. * ==== */
  1486. /** Return the body of the consensus that we're currently trying to build. */
  1487. const char *
  1488. dirvote_get_pending_consensus(void)
  1489. {
  1490. return pending_consensus_body;
  1491. }
  1492. /** Return the signatures that we know for the consensus that we're currently
  1493. * trying to build */
  1494. const char *
  1495. dirvote_get_pending_detached_signatures(void)
  1496. {
  1497. return pending_consensus_signatures;
  1498. }
  1499. /** Return the vote for the authority with the v3 authority identity key
  1500. * digest <b>id</b>. If <b>id</b> is NULL, return our own vote. May return
  1501. * NULL if we have no vote for the authority in question. */
  1502. const cached_dir_t *
  1503. dirvote_get_vote(const char *id)
  1504. {
  1505. if (!pending_vote_list)
  1506. return NULL;
  1507. if (id == NULL) {
  1508. authority_cert_t *c = get_my_v3_authority_cert();
  1509. if (c)
  1510. id = c->cache_info.identity_digest;
  1511. else
  1512. return NULL;
  1513. }
  1514. SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
  1515. if (!memcmp(get_voter(pv->vote)->identity_digest, id, DIGEST_LEN))
  1516. return pv->vote_body);
  1517. return NULL;
  1518. }