consdiff.c 36 KB

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