consdiff.c 33 KB

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