dirvote.c 54 KB

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