consdiff.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  600. "an ed command was missing a range end line number.");
  601. goto error_cleanup;
  602. }
  603. /* Incoherent range. */
  604. if (end <= start) {
  605. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  606. "an invalid range was found in an ed command.");
  607. goto error_cleanup;
  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 == '\0') {
  620. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  621. "a line with no ed command was found");
  622. goto error_cleanup;
  623. }
  624. if (*(endptr2+1) != '\0') {
  625. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  626. "an ed command longer than one char was found.");
  627. goto error_cleanup;
  628. }
  629. char action = *endptr2;
  630. switch (action) {
  631. case 'a':
  632. case 'c':
  633. case 'd':
  634. break;
  635. default:
  636. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  637. "an unrecognised ed command was found.");
  638. goto error_cleanup;
  639. }
  640. /* Add unchanged lines. */
  641. for (; j > end; --j) {
  642. const char *cons_line = smartlist_get(cons1, j-1);
  643. smartlist_add(cons2, tor_strdup(cons_line));
  644. }
  645. /* Ignore removed lines. */
  646. if (action == 'c' || action == 'd') {
  647. while (--j >= start) {
  648. /* Skip line */
  649. }
  650. }
  651. /* Add new lines in reverse order, since it will all be reversed at the
  652. * end.
  653. */
  654. if (action == 'a' || action == 'c') {
  655. int added_end = i;
  656. i++; /* Skip the line with the range and command. */
  657. while (i < diff_len) {
  658. if (!strcmp(smartlist_get(diff, i), ".")) {
  659. break;
  660. }
  661. if (++i == diff_len) {
  662. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  663. "it has lines to be inserted that don't end with a \".\".");
  664. goto error_cleanup;
  665. }
  666. }
  667. int added_i = i-1;
  668. /* It would make no sense to add zero new lines. */
  669. if (added_i == added_end) {
  670. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  671. "it has an ed command that tries to insert zero lines.");
  672. goto error_cleanup;
  673. }
  674. while (added_i > added_end) {
  675. const char *added_line = smartlist_get(diff, added_i--);
  676. smartlist_add(cons2, tor_strdup(added_line));
  677. }
  678. }
  679. }
  680. /* Add remaining unchanged lines. */
  681. for (; j > 0; --j) {
  682. const char *cons_line = smartlist_get(cons1, j-1);
  683. smartlist_add(cons2, tor_strdup(cons_line));
  684. }
  685. /* Reverse the whole thing since we did it from the end. */
  686. smartlist_reverse(cons2);
  687. return cons2;
  688. error_cleanup:
  689. SMARTLIST_FOREACH(cons2, char*, line, tor_free(line));
  690. smartlist_free(cons2);
  691. return NULL;
  692. }
  693. /** Generate a consensus diff as a smartlist from two given consensuses, also
  694. * as smartlists. Will return NULL if the consensus diff could not be
  695. * generated. Neither of the two consensuses are modified in any way, so it's
  696. * up to the caller to free their resources.
  697. */
  698. smartlist_t *
  699. consdiff_gen_diff(smartlist_t *cons1, smartlist_t *cons2,
  700. common_digests_t *digests1, common_digests_t *digests2)
  701. {
  702. smartlist_t *ed_diff = gen_ed_diff(cons1, cons2);
  703. /* ed diff could not be generated - reason already logged by gen_ed_diff. */
  704. if (!ed_diff) {
  705. goto error_cleanup;
  706. }
  707. /* See that the script actually produces what we want. */
  708. smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff);
  709. if (!ed_cons2) {
  710. /* LCOV_EXCL_START -- impossible if diff generation is correct */
  711. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  712. "the generated ed diff could not be tested to successfully generate "
  713. "the target consensus.");
  714. goto error_cleanup;
  715. /* LCOV_EXCL_STOP */
  716. }
  717. int cons2_eq = smartlist_strings_eq(cons2, ed_cons2);
  718. SMARTLIST_FOREACH(ed_cons2, char*, line, tor_free(line));
  719. smartlist_free(ed_cons2);
  720. if (!cons2_eq) {
  721. /* LCOV_EXCL_START -- impossible if diff generation is correct. */
  722. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  723. "the generated ed diff did not generate the target consensus "
  724. "successfully when tested.");
  725. goto error_cleanup;
  726. /* LCOV_EXCL_STOP */
  727. }
  728. char cons1_hash_hex[HEX_DIGEST256_LEN+1];
  729. char cons2_hash_hex[HEX_DIGEST256_LEN+1];
  730. base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
  731. digests1->d[DIGEST_SHA256], DIGEST256_LEN);
  732. base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
  733. digests2->d[DIGEST_SHA256], DIGEST256_LEN);
  734. /* Create the resulting consensus diff. */
  735. smartlist_t *result = smartlist_new();
  736. smartlist_add_asprintf(result, "%s", ns_diff_version);
  737. smartlist_add_asprintf(result, "%s %s %s", hash_token,
  738. cons1_hash_hex, cons2_hash_hex); smartlist_add_all(result, ed_diff);
  739. smartlist_free(ed_diff);
  740. return result;
  741. error_cleanup:
  742. if (ed_diff) {
  743. smartlist_free(ed_diff);
  744. }
  745. return NULL;
  746. }
  747. /** Fetch the digest of the base consensus in the consensus diff, encoded in
  748. * base16 as found in the diff itself. digest1 and digest2 must be of length
  749. * DIGEST256_LEN or larger if not NULL. digest1_hex and digest2_hex must be of
  750. * length HEX_DIGEST256_LEN or larger if not NULL.
  751. */
  752. int
  753. consdiff_get_digests(smartlist_t *diff,
  754. char *digest1, char *digest1_hex,
  755. char *digest2, char *digest2_hex)
  756. {
  757. smartlist_t *hash_words = NULL;
  758. const char *format;
  759. char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
  760. char *cons1_hash_hex, *cons2_hash_hex;
  761. if (smartlist_len(diff) < 2) {
  762. log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
  763. goto error_cleanup;
  764. }
  765. /* Check that it's the format and version we know. */
  766. format = smartlist_get(diff, 0);
  767. if (strcmp(format, ns_diff_version)) {
  768. log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
  769. goto error_cleanup;
  770. }
  771. /* Grab the SHA256 base16 hashes. */
  772. hash_words = smartlist_new();
  773. smartlist_split_string(hash_words, smartlist_get(diff, 1), " ", 0, 0);
  774. /* There have to be three words, the first of which must be hash_token. */
  775. if (smartlist_len(hash_words) != 3 ||
  776. strcmp(smartlist_get(hash_words, 0), hash_token)) {
  777. log_info(LD_CONSDIFF, "The provided consensus diff does not include "
  778. "the necessary digests.");
  779. goto error_cleanup;
  780. }
  781. /* Expected hashes as found in the consensus diff header. They must be of
  782. * length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
  783. * If any of the decodings fail, error to make sure that the hashes are
  784. * proper base16-encoded SHA256 digests.
  785. */
  786. cons1_hash_hex = smartlist_get(hash_words, 1);
  787. cons2_hash_hex = smartlist_get(hash_words, 2);
  788. if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
  789. strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
  790. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  791. "base16-encoded digests of incorrect size.");
  792. goto error_cleanup;
  793. }
  794. if (digest1_hex) {
  795. strlcpy(digest1_hex, cons1_hash_hex, HEX_DIGEST256_LEN+1);
  796. }
  797. if (digest2_hex) {
  798. strlcpy(digest2_hex, cons2_hash_hex, HEX_DIGEST256_LEN+1);
  799. }
  800. if (base16_decode(cons1_hash, DIGEST256_LEN,
  801. cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
  802. base16_decode(cons2_hash, DIGEST256_LEN,
  803. cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
  804. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  805. "malformed digests.");
  806. goto error_cleanup;
  807. }
  808. if (digest1) {
  809. memcpy(digest1, cons1_hash, DIGEST256_LEN);
  810. }
  811. if (digest2) {
  812. memcpy(digest2, cons2_hash, DIGEST256_LEN);
  813. }
  814. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  815. smartlist_free(hash_words);
  816. return 0;
  817. error_cleanup:
  818. if (hash_words) {
  819. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  820. smartlist_free(hash_words);
  821. }
  822. return 1;
  823. }
  824. /** Apply the consensus diff to the given consensus and return a new
  825. * consensus, also as a line-based smartlist. Will return NULL if the diff
  826. * could not be applied. Neither the consensus nor the diff are modified in
  827. * any way, so it's up to the caller to free their resources.
  828. */
  829. char *
  830. consdiff_apply_diff(smartlist_t *cons1, smartlist_t *diff,
  831. common_digests_t *digests1)
  832. {
  833. smartlist_t *cons2 = NULL;
  834. char *cons2_str = NULL;
  835. char e_cons1_hash[DIGEST256_LEN];
  836. char e_cons2_hash[DIGEST256_LEN];
  837. if (consdiff_get_digests(diff,
  838. e_cons1_hash, NULL, e_cons2_hash, NULL) != 0) {
  839. goto error_cleanup;
  840. }
  841. /* See that the consensus that was given to us matches its hash. */
  842. if (fast_memneq(digests1->d[DIGEST_SHA256], e_cons1_hash,
  843. DIGEST256_LEN)) {
  844. char hex_digest1[HEX_DIGEST256_LEN+1];
  845. char e_hex_digest1[HEX_DIGEST256_LEN+1];
  846. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  847. "the base consensus doesn't match the digest as found in "
  848. "the consensus diff header.");
  849. base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
  850. digests1->d[DIGEST_SHA256], DIGEST256_LEN);
  851. base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
  852. e_cons1_hash, DIGEST256_LEN);
  853. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  854. hex_digest1, e_hex_digest1);
  855. goto error_cleanup;
  856. }
  857. /* Grab the ed diff and calculate the resulting consensus. */
  858. /* To avoid copying memory or iterating over all the elements, make a
  859. * read-only smartlist without the two header lines.
  860. */
  861. /* XXXX prop140 abstraction violation; never do this. */
  862. smartlist_t *ed_diff = tor_malloc(sizeof(smartlist_t));
  863. ed_diff->list = diff->list+2;
  864. ed_diff->num_used = diff->num_used-2;
  865. ed_diff->capacity = diff->capacity-2;
  866. cons2 = apply_ed_diff(cons1, ed_diff);
  867. tor_free(ed_diff);
  868. /* ed diff could not be applied - reason already logged by apply_ed_diff. */
  869. if (!cons2) {
  870. goto error_cleanup;
  871. }
  872. cons2_str = smartlist_join_strings(cons2, "\n", 1, NULL);
  873. common_digests_t cons2_digests;
  874. if (router_get_networkstatus_v3_hashes(cons2_str,
  875. &cons2_digests)<0) {
  876. log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
  877. "resulting from applying a consensus diff.");
  878. goto error_cleanup;
  879. }
  880. /* See that the resulting consensus matches its hash. */
  881. if (fast_memneq(cons2_digests.d[DIGEST_SHA256], e_cons2_hash,
  882. DIGEST256_LEN)) {
  883. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  884. "the resulting consensus doesn't match the digest as found in "
  885. "the consensus diff header.");
  886. char hex_digest2[HEX_DIGEST256_LEN+1];
  887. char e_hex_digest2[HEX_DIGEST256_LEN+1];
  888. base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
  889. cons2_digests.d[DIGEST_SHA256], DIGEST256_LEN);
  890. base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
  891. e_cons2_hash, DIGEST256_LEN);
  892. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  893. hex_digest2, e_hex_digest2);
  894. goto error_cleanup;
  895. }
  896. goto done;
  897. error_cleanup:
  898. tor_free(cons2_str); /* Sets it to NULL */
  899. done:
  900. if (cons2) {
  901. SMARTLIST_FOREACH(cons2, char *, cp, tor_free(cp));
  902. smartlist_free(cons2);
  903. }
  904. return cons2_str;
  905. }