consdiff.c 37 KB

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