consdiff.c 33 KB

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