consdiff.c 32 KB

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