consdiff.c 33 KB

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