consdiff.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /* Copyright (c) 2014, Daniel Martí
  2. * Copyright (c) 2014, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file consdiff.c
  6. * \brief Consensus diff implementation, including both the generation and the
  7. * application of diffs in a minimal ed format.
  8. *
  9. * The consensus diff application is done in consdiff_apply_diff, which relies
  10. * on apply_ed_diff for the main ed diff part and on some digest helper
  11. * functions to check the digest hashes found in the consensus diff header.
  12. *
  13. * The consensus diff generation is more complex. consdiff_gen_diff generates
  14. * it, relying on gen_ed_diff to generate the ed diff and some digest helper
  15. * functions to generate the digest hashes.
  16. *
  17. * gen_ed_diff is the tricky bit. In it simplest form, it will take quadratic
  18. * time and linear space to generate an ed diff given two smartlists. As shown
  19. * in its comment section, calling calc_changes on the entire two consensuses
  20. * will calculate what is to be added and what is to be deleted in the diff.
  21. * Its comment section briefly explains how it works.
  22. *
  23. * In our case specific to consensuses, we take advantage of the fact that
  24. * consensuses list routers sorted by their identities. We use that
  25. * information to avoid running calc_changes on the whole smartlists.
  26. * gen_ed_diff will navigate through the two consensuses identity by identity
  27. * and will send small couples of slices to calc_changes, keeping the running
  28. * time near-linear. This is explained in more detail in the gen_ed_diff
  29. * comments.
  30. **/
  31. #define CONSDIFF_PRIVATE
  32. #include "or.h"
  33. #include "consdiff.h"
  34. #include "routerparse.h"
  35. static const char* ns_diff_version = "network-status-diff-version 1";
  36. static const char* hash_token = "hash";
  37. STATIC int
  38. consensus_compute_digest(const char *cons,
  39. consensus_digest_t *digest_out)
  40. {
  41. int r = crypto_digest256((char*)digest_out->sha3_256,
  42. cons, strlen(cons), DIGEST_SHA3_256);
  43. return r;
  44. }
  45. /** Create (allocate) a new slice from a smartlist. Assumes that the start
  46. * and the end indexes are within the bounds of the initial smartlist. The end
  47. * element is not part of the resulting slice. If end is -1, the slice is to
  48. * reach the end of the smartlist.
  49. */
  50. STATIC smartlist_slice_t *
  51. smartlist_slice(const smartlist_t *list, int start, int end)
  52. {
  53. int list_len = smartlist_len(list);
  54. tor_assert(start >= 0);
  55. tor_assert(start <= list_len);
  56. if (end == -1) {
  57. end = list_len;
  58. }
  59. tor_assert(start <= end);
  60. smartlist_slice_t *slice = tor_malloc(sizeof(smartlist_slice_t));
  61. slice->list = list;
  62. slice->offset = start;
  63. slice->len = end - start;
  64. return slice;
  65. }
  66. /** Helper: Compute the longest common subsequence lengths for the two slices.
  67. * Used as part of the diff generation to find the column at which to split
  68. * slice2 while still having the optimal solution.
  69. * If direction is -1, the navigation is reversed. Otherwise it must be 1.
  70. * The length of the resulting integer array is that of the second slice plus
  71. * one.
  72. */
  73. STATIC int *
  74. lcs_lengths(const smartlist_slice_t *slice1, const smartlist_slice_t *slice2,
  75. int direction)
  76. {
  77. size_t a_size = sizeof(int) * (slice2->len+1);
  78. /* Resulting lcs lengths. */
  79. int *result = tor_malloc_zero(a_size);
  80. /* Copy of the lcs lengths from the last iteration. */
  81. int *prev = tor_malloc(a_size);
  82. tor_assert(direction == 1 || direction == -1);
  83. int si = slice1->offset;
  84. if (direction == -1) {
  85. si += (slice1->len-1);
  86. }
  87. for (int i = 0; i < slice1->len; ++i, si+=direction) {
  88. const char *line1 = smartlist_get(slice1->list, si);
  89. /* Store the last results. */
  90. memcpy(prev, result, a_size);
  91. int sj = slice2->offset;
  92. if (direction == -1) {
  93. sj += (slice2->len-1);
  94. }
  95. for (int j = 0; j < slice2->len; ++j, sj+=direction) {
  96. const char *line2 = smartlist_get(slice2->list, sj);
  97. if (!strcmp(line1, line2)) {
  98. /* If the lines are equal, the lcs is one line longer. */
  99. result[j + 1] = prev[j] + 1;
  100. } else {
  101. /* If not, see what lcs parent path is longer. */
  102. result[j + 1] = MAX(result[j], prev[j + 1]);
  103. }
  104. }
  105. }
  106. tor_free(prev);
  107. return result;
  108. }
  109. /** Helper: Trim any number of lines that are equally at the start or the end
  110. * of both slices.
  111. */
  112. STATIC void
  113. trim_slices(smartlist_slice_t *slice1, smartlist_slice_t *slice2)
  114. {
  115. while (slice1->len>0 && slice2->len>0) {
  116. const char *line1 = smartlist_get(slice1->list, slice1->offset);
  117. const char *line2 = smartlist_get(slice2->list, slice2->offset);
  118. if (strcmp(line1, line2)) {
  119. break;
  120. }
  121. slice1->offset++; slice1->len--;
  122. slice2->offset++; slice2->len--;
  123. }
  124. int i1 = (slice1->offset+slice1->len)-1;
  125. int i2 = (slice2->offset+slice2->len)-1;
  126. while (slice1->len>0 && slice2->len>0) {
  127. const char *line1 = smartlist_get(slice1->list, i1);
  128. const char *line2 = smartlist_get(slice2->list, i2);
  129. if (strcmp(line1, line2)) {
  130. break;
  131. }
  132. i1--;
  133. slice1->len--;
  134. i2--;
  135. slice2->len--;
  136. }
  137. }
  138. /** Like smartlist_string_pos, but limited to the bounds of the slice.
  139. */
  140. STATIC int
  141. smartlist_slice_string_pos(const smartlist_slice_t *slice, const char *string)
  142. {
  143. int end = slice->offset + slice->len;
  144. for (int i = slice->offset; i < end; ++i) {
  145. const char *el = smartlist_get(slice->list, i);
  146. if (!strcmp(el, string)) {
  147. return i;
  148. }
  149. }
  150. return -1;
  151. }
  152. /** Helper: Set all the appropriate changed booleans to true. The first slice
  153. * must be of length 0 or 1. All the lines of slice1 and slice2 which are not
  154. * present in the other slice will be set to changed in their bool array.
  155. * The two changed bool arrays are passed in the same order as the slices.
  156. */
  157. STATIC void
  158. set_changed(bitarray_t *changed1, bitarray_t *changed2,
  159. const smartlist_slice_t *slice1, const smartlist_slice_t *slice2)
  160. {
  161. int toskip = -1;
  162. tor_assert(slice1->len == 0 || slice1->len == 1);
  163. if (slice1->len == 1) {
  164. const char *line_common = smartlist_get(slice1->list, slice1->offset);
  165. toskip = smartlist_slice_string_pos(slice2, line_common);
  166. if (toskip == -1) {
  167. bitarray_set(changed1, slice1->offset);
  168. }
  169. }
  170. int end = slice2->offset + slice2->len;
  171. for (int i = slice2->offset; i < end; ++i) {
  172. if (i != toskip) {
  173. bitarray_set(changed2, i);
  174. }
  175. }
  176. }
  177. /*
  178. * Helper: Given that slice1 has been split by half into top and bot, we want
  179. * to fetch the column at which to split slice2 so that we are still on track
  180. * to the optimal diff solution, i.e. the shortest one. We use lcs_lengths
  181. * since the shortest diff is just another way to say the longest common
  182. * subsequence.
  183. */
  184. static int
  185. optimal_column_to_split(const smartlist_slice_t *top,
  186. const smartlist_slice_t *bot,
  187. const smartlist_slice_t *slice2)
  188. {
  189. int *lens_top = lcs_lengths(top, slice2, 1);
  190. int *lens_bot = lcs_lengths(bot, slice2, -1);
  191. int column=0, max_sum=-1;
  192. for (int i = 0; i < slice2->len+1; ++i) {
  193. int sum = lens_top[i] + lens_bot[slice2->len-i];
  194. if (sum > max_sum) {
  195. column = i;
  196. max_sum = sum;
  197. }
  198. }
  199. tor_free(lens_top);
  200. tor_free(lens_bot);
  201. return column;
  202. }
  203. /**
  204. * Helper: Figure out what elements are new or gone on the second smartlist
  205. * relative to the first smartlist, and store the booleans in the bitarrays.
  206. * True on the first bitarray means the element is gone, true on the second
  207. * bitarray means it's new.
  208. *
  209. * In its base case, either of the smartlists is of length <= 1 and we can
  210. * quickly see what elements are new or are gone. In the other case, we will
  211. * split one smartlist by half and we'll use optimal_column_to_split to find
  212. * the optimal column at which to split the second smartlist so that we are
  213. * finding the smallest diff possible.
  214. */
  215. STATIC void
  216. calc_changes(smartlist_slice_t *slice1,
  217. smartlist_slice_t *slice2,
  218. bitarray_t *changed1, bitarray_t *changed2)
  219. {
  220. trim_slices(slice1, slice2);
  221. if (slice1->len <= 1) {
  222. set_changed(changed1, changed2, slice1, slice2);
  223. } else if (slice2->len <= 1) {
  224. set_changed(changed2, changed1, slice2, slice1);
  225. /* Keep on splitting the slices in two. */
  226. } else {
  227. smartlist_slice_t *top, *bot, *left, *right;
  228. /* Split the first slice in half. */
  229. int mid = slice1->len/2;
  230. top = smartlist_slice(slice1->list, slice1->offset, slice1->offset+mid);
  231. bot = smartlist_slice(slice1->list, slice1->offset+mid,
  232. slice1->offset+slice1->len);
  233. /* Split the second slice by the optimal column. */
  234. int mid2 = optimal_column_to_split(top, bot, slice2);
  235. left = smartlist_slice(slice2->list, slice2->offset, slice2->offset+mid2);
  236. right = smartlist_slice(slice2->list, slice2->offset+mid2,
  237. slice2->offset+slice2->len);
  238. calc_changes(top, left, changed1, changed2);
  239. calc_changes(bot, right, changed1, changed2);
  240. tor_free(top);
  241. tor_free(bot);
  242. tor_free(left);
  243. tor_free(right);
  244. }
  245. }
  246. /* This table is from crypto.c. The SP and PAD defines are different. */
  247. #define X 255
  248. #define SP X
  249. #define PAD X
  250. static const uint8_t base64_compare_table[256] = {
  251. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X,
  252. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  253. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  254. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  255. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  256. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  257. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  258. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  259. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  260. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  261. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  262. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  263. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  264. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  265. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  266. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  267. };
  268. /** Helper: Get the identity hash from a router line, assuming that the line
  269. * at least appears to be a router line and thus starts with "r ".
  270. */
  271. STATIC const char *
  272. get_id_hash(const char *r_line)
  273. {
  274. r_line += strlen("r ");
  275. /* Skip the router name. */
  276. const char *hash = strchr(r_line, ' ');
  277. if (!hash) {
  278. return NULL;
  279. }
  280. hash++;
  281. const char *hash_end = hash;
  282. /* Stop when the first non-base64 character is found. Use unsigned chars to
  283. * avoid negative indexes causing crashes.
  284. */
  285. while (base64_compare_table[*((unsigned char*)hash_end)] != X) {
  286. hash_end++;
  287. }
  288. /* Empty hash. */
  289. if (hash_end == hash) {
  290. return NULL;
  291. }
  292. return hash;
  293. }
  294. /** Helper: Check that a line is a valid router entry. We must at least be
  295. * able to fetch a proper identity hash from it for it to be valid.
  296. */
  297. STATIC int
  298. is_valid_router_entry(const char *line)
  299. {
  300. if (strcmpstart(line, "r ") != 0) {
  301. return 0;
  302. }
  303. return (get_id_hash(line) != NULL);
  304. }
  305. /** Helper: Find the next router line starting at the current position.
  306. * Assumes that cur is lower than the length of the smartlist, i.e. it is a
  307. * line within the bounds of the consensus. The only exception is when we
  308. * don't want to skip the first line, in which case cur will be -1.
  309. */
  310. STATIC int
  311. next_router(const smartlist_t *cons, int cur)
  312. {
  313. int len = smartlist_len(cons);
  314. tor_assert(cur >= -1 && cur < len);
  315. if (++cur >= len) {
  316. return len;
  317. }
  318. const char *line = smartlist_get(cons, cur);
  319. while (!is_valid_router_entry(line)) {
  320. if (++cur >= len) {
  321. return len;
  322. }
  323. line = smartlist_get(cons, cur);
  324. }
  325. return cur;
  326. }
  327. /** Helper: compare two base64-encoded identity hashes which may be of
  328. * different lengths. Comparison ends when the first non-base64 char is found.
  329. */
  330. STATIC int
  331. base64cmp(const char *hash1, const char *hash2)
  332. {
  333. /* NULL is always lower, useful for last_hash which starts at NULL. */
  334. if (!hash1 && !hash2) {
  335. return 0;
  336. }
  337. if (!hash1) {
  338. return -1;
  339. }
  340. if (!hash2) {
  341. return 1;
  342. }
  343. /* Don't index with a char; char may be signed. */
  344. const unsigned char *a = (unsigned char*)hash1;
  345. const unsigned char *b = (unsigned char*)hash2;
  346. while (1) {
  347. uint8_t av = base64_compare_table[*a];
  348. uint8_t bv = base64_compare_table[*b];
  349. if (av == X) {
  350. if (bv == X) {
  351. /* Both ended with exactly the same characters. */
  352. return 0;
  353. } else {
  354. /* hash2 goes on longer than hash1 and thus hash1 is lower. */
  355. return -1;
  356. }
  357. } else if (bv == X) {
  358. /* hash1 goes on longer than hash2 and thus hash1 is greater. */
  359. return 1;
  360. } else if (av < bv) {
  361. /* The first difference shows that hash1 is lower. */
  362. return -1;
  363. } else if (av > bv) {
  364. /* The first difference shows that hash1 is greater. */
  365. return 1;
  366. } else {
  367. a++;
  368. b++;
  369. }
  370. }
  371. }
  372. /** Generate an ed diff as a smartlist from two consensuses, also given as
  373. * smartlists. Will return NULL if the diff could not be generated, which can
  374. * happen if any lines the script had to add matched "." or if the routers
  375. * were not properly ordered.
  376. *
  377. * This implementation is consensus-specific. To generate an ed diff for any
  378. * given input in quadratic time, you can replace all the code until the
  379. * navigation in reverse order with the following:
  380. *
  381. * int len1 = smartlist_len(cons1);
  382. * int len2 = smartlist_len(cons2);
  383. * bitarray_t *changed1 = bitarray_init_zero(len1);
  384. * bitarray_t *changed2 = bitarray_init_zero(len2);
  385. * cons1_sl = smartlist_slice(cons1, 0, -1);
  386. * cons2_sl = smartlist_slice(cons2, 0, -1);
  387. * calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  388. */
  389. STATIC smartlist_t *
  390. gen_ed_diff(const smartlist_t *cons1, const smartlist_t *cons2)
  391. {
  392. int len1 = smartlist_len(cons1);
  393. int len2 = smartlist_len(cons2);
  394. smartlist_t *result = smartlist_new();
  395. /* Initialize the changed bitarrays to zero, so that calc_changes only needs
  396. * to set the ones that matter and leave the rest untouched.
  397. */
  398. bitarray_t *changed1 = bitarray_init_zero(len1);
  399. bitarray_t *changed2 = bitarray_init_zero(len2);
  400. int i1=-1, i2=-1;
  401. int start1=0, start2=0;
  402. const char *hash1 = NULL;
  403. const char *hash2 = NULL;
  404. /* To check that hashes are ordered properly */
  405. const char *last_hash1 = NULL;
  406. const char *last_hash2 = NULL;
  407. /* i1 and i2 are initialized at the first line of each consensus. They never
  408. * reach past len1 and len2 respectively, since next_router doesn't let that
  409. * happen. i1 and i2 are advanced by at least one line at each iteration as
  410. * long as they have not yet reached len1 and len2, so the loop is
  411. * guaranteed to end, and each pair of (i1,i2) will be inspected at most
  412. * once.
  413. */
  414. while (i1 < len1 || i2 < len2) {
  415. /* Advance each of the two navigation positions by one router entry if not
  416. * yet at the end.
  417. */
  418. if (i1 < len1) {
  419. i1 = next_router(cons1, i1);
  420. if (i1 != len1) {
  421. last_hash1 = hash1;
  422. hash1 = get_id_hash(smartlist_get(cons1, i1));
  423. if (base64cmp(hash1, last_hash1) <= 0) {
  424. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  425. "the base consensus doesn't have its router entries "
  426. "sorted properly.");
  427. goto error_cleanup;
  428. }
  429. }
  430. }
  431. if (i2 < len2) {
  432. i2 = next_router(cons2, i2);
  433. if (i2 != len2) {
  434. last_hash2 = hash2;
  435. hash2 = get_id_hash(smartlist_get(cons2, i2));
  436. if (base64cmp(hash2, last_hash2) <= 0) {
  437. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  438. "the target consensus doesn't have its router entries "
  439. "sorted properly.");
  440. goto error_cleanup;
  441. }
  442. }
  443. }
  444. /* If we have reached the end of both consensuses, there is no need to
  445. * compare hashes anymore, since this is the last iteration.
  446. */
  447. if (i1 < len1 || i2 < len2) {
  448. /* Keep on advancing the lower (by identity hash sorting) position until
  449. * we have two matching positions. The only other possible outcome is
  450. * that a lower position reaches the end of the consensus before it can
  451. * reach a hash that is no longer the lower one. Since there will always
  452. * be a lower hash for as long as the loop runs, one of the two indexes
  453. * will always be incremented, thus assuring that the loop must end
  454. * after a finite number of iterations. If that cannot be because said
  455. * consensus has already reached the end, both are extended to their
  456. * respecting ends since we are done.
  457. */
  458. int cmp = base64cmp(hash1, hash2);
  459. while (cmp != 0) {
  460. if (i1 < len1 && cmp < 0) {
  461. i1 = next_router(cons1, i1);
  462. if (i1 == len1) {
  463. /* We finished the first consensus, so grab all the remaining
  464. * lines of the second consensus and finish up.
  465. */
  466. i2 = len2;
  467. break;
  468. }
  469. last_hash1 = hash1;
  470. hash1 = get_id_hash(smartlist_get(cons1, i1));
  471. if (base64cmp(hash1, last_hash1) <= 0) {
  472. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff "
  473. "because the base consensus doesn't have its router entries "
  474. "sorted properly.");
  475. goto error_cleanup;
  476. }
  477. } else if (i2 < len2 && cmp > 0) {
  478. i2 = next_router(cons2, i2);
  479. if (i2 == len2) {
  480. /* We finished the second consensus, so grab all the remaining
  481. * lines of the first consensus and finish up.
  482. */
  483. i1 = len1;
  484. break;
  485. }
  486. last_hash2 = hash2;
  487. hash2 = get_id_hash(smartlist_get(cons2, i2));
  488. if (base64cmp(hash2, last_hash2) <= 0) {
  489. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff "
  490. "because the target consensus doesn't have its router entries "
  491. "sorted properly.");
  492. goto error_cleanup;
  493. }
  494. } else {
  495. i1 = len1;
  496. i2 = len2;
  497. break;
  498. }
  499. cmp = base64cmp(hash1, hash2);
  500. }
  501. }
  502. /* Make slices out of these chunks (up to the common router entry) and
  503. * calculate the changes for them.
  504. * Error if any of the two slices are longer than 10K lines. That should
  505. * never happen with any pair of real consensuses. Feeding more than 10K
  506. * lines to calc_changes would be very slow anyway.
  507. */
  508. #define MAX_LINE_COUNT (10000)
  509. if (i1-start1 > MAX_LINE_COUNT || i2-start2 > MAX_LINE_COUNT) {
  510. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  511. "we found too few common router ids.");
  512. goto error_cleanup;
  513. }
  514. smartlist_slice_t *cons1_sl = smartlist_slice(cons1, start1, i1);
  515. smartlist_slice_t *cons2_sl = smartlist_slice(cons2, start2, i2);
  516. calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  517. tor_free(cons1_sl);
  518. tor_free(cons2_sl);
  519. start1 = i1, start2 = i2;
  520. }
  521. /* Navigate the changes in reverse order and generate one ed command for
  522. * each chunk of changes.
  523. */
  524. i1=len1-1, i2=len2-1;
  525. while (i1 > 0 || i2 > 0) {
  526. int start1x, start2x, end1, end2, added, deleted;
  527. /* We are at a point were no changed bools are true, so just keep going. */
  528. if (!(i1 >= 0 && bitarray_is_set(changed1, i1)) &&
  529. !(i2 >= 0 && bitarray_is_set(changed2, i2))) {
  530. if (i1 >= 0) {
  531. i1--;
  532. }
  533. if (i2 >= 0) {
  534. i2--;
  535. }
  536. continue;
  537. }
  538. end1 = i1, end2 = i2;
  539. /* Grab all contiguous changed lines */
  540. while (i1 >= 0 && bitarray_is_set(changed1, i1)) {
  541. i1--;
  542. }
  543. while (i2 >= 0 && bitarray_is_set(changed2, i2)) {
  544. i2--;
  545. }
  546. start1x = i1+1, start2x = i2+1;
  547. added = end2-i2, deleted = end1-i1;
  548. if (added == 0) {
  549. if (deleted == 1) {
  550. smartlist_add_asprintf(result, "%id", start1x+1);
  551. } else {
  552. smartlist_add_asprintf(result, "%i,%id", start1x+1, start1x+deleted);
  553. }
  554. } else {
  555. int i;
  556. if (deleted == 0) {
  557. smartlist_add_asprintf(result, "%ia", start1x);
  558. } else if (deleted == 1) {
  559. smartlist_add_asprintf(result, "%ic", start1x+1);
  560. } else {
  561. smartlist_add_asprintf(result, "%i,%ic", start1x+1, start1x+deleted);
  562. }
  563. for (i = start2x; i <= end2; ++i) {
  564. const char *line = smartlist_get(cons2, i);
  565. if (!strcmp(line, ".")) {
  566. log_warn(LD_CONSDIFF, "Cannot generate consensus diff because "
  567. "one of the lines to be added is \".\".");
  568. goto error_cleanup;
  569. }
  570. smartlist_add(result, tor_strdup(line));
  571. }
  572. smartlist_add_asprintf(result, ".");
  573. }
  574. }
  575. bitarray_free(changed1);
  576. bitarray_free(changed2);
  577. return result;
  578. error_cleanup:
  579. bitarray_free(changed1);
  580. bitarray_free(changed2);
  581. SMARTLIST_FOREACH(result, char*, line, tor_free(line));
  582. smartlist_free(result);
  583. return NULL;
  584. }
  585. /** Apply the ed diff to the consensus and return a new consensus, also as a
  586. * line-based smartlist. Will return NULL if the ed diff is not properly
  587. * formatted.
  588. */
  589. STATIC smartlist_t *
  590. apply_ed_diff(const smartlist_t *cons1, const smartlist_t *diff)
  591. {
  592. int diff_len = smartlist_len(diff);
  593. int j = smartlist_len(cons1);
  594. smartlist_t *cons2 = smartlist_new();
  595. for (int i=0; i<diff_len; ++i) {
  596. const char *diff_line = smartlist_get(diff, i);
  597. char *endptr1, *endptr2;
  598. int start = (int)strtol(diff_line, &endptr1, 10);
  599. int end;
  600. if (endptr1 == diff_line) {
  601. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  602. "an ed command was missing a line number.");
  603. goto error_cleanup;
  604. }
  605. /* Two-item range */
  606. if (*endptr1 == ',') {
  607. end = (int)strtol(endptr1+1, &endptr2, 10);
  608. if (endptr2 == endptr1+1) {
  609. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  610. "an ed command was missing a range end line number.");
  611. goto error_cleanup;
  612. }
  613. /* Incoherent range. */
  614. if (end <= start) {
  615. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  616. "an invalid range was found in an ed command.");
  617. goto error_cleanup;
  618. }
  619. /* We'll take <n1> as <n1>,<n1> for simplicity. */
  620. } else {
  621. endptr2 = endptr1;
  622. end = start;
  623. }
  624. if (end > j) {
  625. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  626. "its commands are not properly sorted in reverse order.");
  627. goto error_cleanup;
  628. }
  629. if (*endptr2 == '\0') {
  630. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  631. "a line with no ed command was found");
  632. goto error_cleanup;
  633. }
  634. if (*(endptr2+1) != '\0') {
  635. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  636. "an ed command longer than one char was found.");
  637. goto error_cleanup;
  638. }
  639. char action = *endptr2;
  640. switch (action) {
  641. case 'a':
  642. case 'c':
  643. case 'd':
  644. break;
  645. default:
  646. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  647. "an unrecognised ed command was found.");
  648. goto error_cleanup;
  649. }
  650. /* Add unchanged lines. */
  651. for (; j > end; --j) {
  652. const char *cons_line = smartlist_get(cons1, j-1);
  653. smartlist_add(cons2, tor_strdup(cons_line));
  654. }
  655. /* Ignore removed lines. */
  656. if (action == 'c' || action == 'd') {
  657. while (--j >= start) {
  658. /* Skip line */
  659. }
  660. }
  661. /* Add new lines in reverse order, since it will all be reversed at the
  662. * end.
  663. */
  664. if (action == 'a' || action == 'c') {
  665. int added_end = i;
  666. i++; /* Skip the line with the range and command. */
  667. while (i < diff_len) {
  668. if (!strcmp(smartlist_get(diff, i), ".")) {
  669. break;
  670. }
  671. if (++i == diff_len) {
  672. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  673. "it has lines to be inserted that don't end with a \".\".");
  674. goto error_cleanup;
  675. }
  676. }
  677. int added_i = i-1;
  678. /* It would make no sense to add zero new lines. */
  679. if (added_i == added_end) {
  680. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  681. "it has an ed command that tries to insert zero lines.");
  682. goto error_cleanup;
  683. }
  684. while (added_i > added_end) {
  685. const char *added_line = smartlist_get(diff, added_i--);
  686. smartlist_add(cons2, tor_strdup(added_line));
  687. }
  688. }
  689. }
  690. /* Add remaining unchanged lines. */
  691. for (; j > 0; --j) {
  692. const char *cons_line = smartlist_get(cons1, j-1);
  693. smartlist_add(cons2, tor_strdup(cons_line));
  694. }
  695. /* Reverse the whole thing since we did it from the end. */
  696. smartlist_reverse(cons2);
  697. return cons2;
  698. error_cleanup:
  699. SMARTLIST_FOREACH(cons2, char*, line, tor_free(line));
  700. smartlist_free(cons2);
  701. return NULL;
  702. }
  703. /** Generate a consensus diff as a smartlist from two given consensuses, also
  704. * as smartlists. Will return NULL if the consensus diff could not be
  705. * generated. Neither of the two consensuses are modified in any way, so it's
  706. * up to the caller to free their resources.
  707. */
  708. smartlist_t *
  709. consdiff_gen_diff(const smartlist_t *cons1, const smartlist_t *cons2,
  710. const consensus_digest_t *digests1,
  711. const consensus_digest_t *digests2)
  712. {
  713. smartlist_t *ed_diff = gen_ed_diff(cons1, cons2);
  714. /* ed diff could not be generated - reason already logged by gen_ed_diff. */
  715. if (!ed_diff) {
  716. goto error_cleanup;
  717. }
  718. /* See that the script actually produces what we want. */
  719. smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff);
  720. if (!ed_cons2) {
  721. /* LCOV_EXCL_START -- impossible if diff generation is correct */
  722. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  723. "the generated ed diff could not be tested to successfully generate "
  724. "the target consensus.");
  725. goto error_cleanup;
  726. /* LCOV_EXCL_STOP */
  727. }
  728. int cons2_eq = smartlist_strings_eq(cons2, ed_cons2);
  729. SMARTLIST_FOREACH(ed_cons2, char*, line, tor_free(line));
  730. smartlist_free(ed_cons2);
  731. if (!cons2_eq) {
  732. /* LCOV_EXCL_START -- impossible if diff generation is correct. */
  733. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  734. "the generated ed diff did not generate the target consensus "
  735. "successfully when tested.");
  736. goto error_cleanup;
  737. /* LCOV_EXCL_STOP */
  738. }
  739. char cons1_hash_hex[HEX_DIGEST256_LEN+1];
  740. char cons2_hash_hex[HEX_DIGEST256_LEN+1];
  741. base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
  742. (const char*)digests1->sha3_256, DIGEST256_LEN);
  743. base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
  744. (const char*)digests2->sha3_256, DIGEST256_LEN);
  745. /* Create the resulting consensus diff. */
  746. smartlist_t *result = smartlist_new();
  747. smartlist_add_asprintf(result, "%s", ns_diff_version);
  748. smartlist_add_asprintf(result, "%s %s %s", hash_token,
  749. cons1_hash_hex, cons2_hash_hex);
  750. smartlist_add_all(result, ed_diff);
  751. smartlist_free(ed_diff);
  752. return result;
  753. error_cleanup:
  754. if (ed_diff) {
  755. /* LCOV_EXCL_START -- ed_diff is NULL except in unreachable cases above */
  756. SMARTLIST_FOREACH(ed_diff, char *, cp, tor_free(cp));
  757. smartlist_free(ed_diff);
  758. /* LCOV_EXCL_STOP */
  759. }
  760. return NULL;
  761. }
  762. /** Fetch the digest of the base consensus in the consensus diff, encoded in
  763. * base16 as found in the diff itself. digest1_out and digest2_out must be of
  764. * length DIGEST256_LEN or larger if not NULL.
  765. */
  766. int
  767. consdiff_get_digests(const smartlist_t *diff,
  768. char *digest1_out,
  769. char *digest2_out)
  770. {
  771. smartlist_t *hash_words = NULL;
  772. const char *format;
  773. char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
  774. char *cons1_hash_hex, *cons2_hash_hex;
  775. if (smartlist_len(diff) < 2) {
  776. log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
  777. goto error_cleanup;
  778. }
  779. /* Check that it's the format and version we know. */
  780. format = smartlist_get(diff, 0);
  781. if (strcmp(format, ns_diff_version)) {
  782. log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
  783. goto error_cleanup;
  784. }
  785. /* Grab the base16 digests. */
  786. hash_words = smartlist_new();
  787. smartlist_split_string(hash_words, smartlist_get(diff, 1), " ", 0, 0);
  788. /* There have to be three words, the first of which must be hash_token. */
  789. if (smartlist_len(hash_words) != 3 ||
  790. strcmp(smartlist_get(hash_words, 0), hash_token)) {
  791. log_info(LD_CONSDIFF, "The provided consensus diff does not include "
  792. "the necessary digests.");
  793. goto error_cleanup;
  794. }
  795. /* Expected hashes as found in the consensus diff header. They must be of
  796. * length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
  797. * If any of the decodings fail, error to make sure that the hashes are
  798. * proper base16-encoded digests.
  799. */
  800. cons1_hash_hex = smartlist_get(hash_words, 1);
  801. cons2_hash_hex = smartlist_get(hash_words, 2);
  802. if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
  803. strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
  804. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  805. "base16-encoded digests of incorrect size.");
  806. goto error_cleanup;
  807. }
  808. if (base16_decode(cons1_hash, DIGEST256_LEN,
  809. cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
  810. base16_decode(cons2_hash, DIGEST256_LEN,
  811. cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
  812. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  813. "malformed digests.");
  814. goto error_cleanup;
  815. }
  816. if (digest1_out) {
  817. memcpy(digest1_out, cons1_hash, DIGEST256_LEN);
  818. }
  819. if (digest2_out) {
  820. memcpy(digest2_out, cons2_hash, DIGEST256_LEN);
  821. }
  822. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  823. smartlist_free(hash_words);
  824. return 0;
  825. error_cleanup:
  826. if (hash_words) {
  827. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  828. smartlist_free(hash_words);
  829. }
  830. return 1;
  831. }
  832. /** Apply the consensus diff to the given consensus and return a new
  833. * consensus, also as a line-based smartlist. Will return NULL if the diff
  834. * could not be applied. Neither the consensus nor the diff are modified in
  835. * any way, so it's up to the caller to free their resources.
  836. */
  837. char *
  838. consdiff_apply_diff(const smartlist_t *cons1,
  839. const smartlist_t *diff,
  840. const consensus_digest_t *digests1)
  841. {
  842. smartlist_t *cons2 = NULL;
  843. char *cons2_str = NULL;
  844. char e_cons1_hash[DIGEST256_LEN];
  845. char e_cons2_hash[DIGEST256_LEN];
  846. if (consdiff_get_digests(diff, e_cons1_hash, e_cons2_hash) != 0) {
  847. goto error_cleanup;
  848. }
  849. /* See that the consensus that was given to us matches its hash. */
  850. if (fast_memneq(digests1->sha3_256, e_cons1_hash,
  851. DIGEST256_LEN)) {
  852. char hex_digest1[HEX_DIGEST256_LEN+1];
  853. char e_hex_digest1[HEX_DIGEST256_LEN+1];
  854. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  855. "the base consensus doesn't match the digest as found in "
  856. "the consensus diff header.");
  857. base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
  858. (const char *)digests1->sha3_256, DIGEST256_LEN);
  859. base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
  860. e_cons1_hash, DIGEST256_LEN);
  861. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  862. hex_digest1, e_hex_digest1);
  863. goto error_cleanup;
  864. }
  865. /* Grab the ed diff and calculate the resulting consensus. */
  866. /* To avoid copying memory or iterating over all the elements, make a
  867. * read-only smartlist without the two header lines.
  868. */
  869. /* XXXX prop140 abstraction violation; never do this. */
  870. smartlist_t *ed_diff = tor_malloc(sizeof(smartlist_t));
  871. ed_diff->list = diff->list+2;
  872. ed_diff->num_used = diff->num_used-2;
  873. ed_diff->capacity = diff->capacity-2;
  874. cons2 = apply_ed_diff(cons1, ed_diff);
  875. tor_free(ed_diff);
  876. /* ed diff could not be applied - reason already logged by apply_ed_diff. */
  877. if (!cons2) {
  878. goto error_cleanup;
  879. }
  880. cons2_str = smartlist_join_strings(cons2, "\n", 1, NULL);
  881. consensus_digest_t cons2_digests;
  882. if (consensus_compute_digest(cons2_str, &cons2_digests) < 0) {
  883. /* LCOV_EXCL_START -- digest can't fail */
  884. log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
  885. "resulting from applying a consensus diff.");
  886. goto error_cleanup;
  887. /* LCOV_EXCL_STOP */
  888. }
  889. /* See that the resulting consensus matches its hash. */
  890. if (fast_memneq(cons2_digests.sha3_256, e_cons2_hash,
  891. DIGEST256_LEN)) {
  892. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  893. "the resulting consensus doesn't match the digest as found in "
  894. "the consensus diff header.");
  895. char hex_digest2[HEX_DIGEST256_LEN+1];
  896. char e_hex_digest2[HEX_DIGEST256_LEN+1];
  897. base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
  898. (const char *)cons2_digests.sha3_256, DIGEST256_LEN);
  899. base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
  900. e_cons2_hash, DIGEST256_LEN);
  901. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  902. hex_digest2, e_hex_digest2);
  903. goto error_cleanup;
  904. }
  905. goto done;
  906. error_cleanup:
  907. tor_free(cons2_str); /* Sets it to NULL */
  908. done:
  909. if (cons2) {
  910. SMARTLIST_FOREACH(cons2, char *, cp, tor_free(cp));
  911. smartlist_free(cons2);
  912. }
  913. return cons2_str;
  914. }