consdiff.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. * The allocation strategy tries to save time and memory by avoiding needless
  32. * copies. Instead of actually splitting the inputs into separate strings, we
  33. * allocate cdline_t objects, each of which represents a line in the original
  34. * object or in the output. We use memarea_t allocators to manage the
  35. * temporary memory we use when generating or applying diffs.
  36. **/
  37. #define CONSDIFF_PRIVATE
  38. #include "or.h"
  39. #include "consdiff.h"
  40. #include "memarea.h"
  41. #include "routerparse.h"
  42. static const char* ns_diff_version = "network-status-diff-version 1";
  43. static const char* hash_token = "hash";
  44. static char *consensus_join_lines(const smartlist_t *inp);
  45. /** Return true iff a and b have the same contents. */
  46. STATIC int
  47. lines_eq(const cdline_t *a, const cdline_t *b)
  48. {
  49. return a->len == b->len && fast_memeq(a->s, b->s, a->len);
  50. }
  51. /** Return true iff a has the same contents as the nul-terminated string b. */
  52. STATIC int
  53. line_str_eq(const cdline_t *a, const char *b)
  54. {
  55. const size_t len = strlen(b);
  56. tor_assert(len <= UINT32_MAX);
  57. cdline_t bline = { b, (uint32_t)len };
  58. return lines_eq(a, &bline);
  59. }
  60. /** Add a cdline_t to <b>lst</b> holding as its contents the nul-terminated
  61. * string s. Use the provided memory area for storage. */
  62. STATIC void
  63. smartlist_add_linecpy(smartlist_t *lst, memarea_t *area, const char *s)
  64. {
  65. size_t len = strlen(s);
  66. const char *ss = memarea_memdup(area, s, len);
  67. cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
  68. line->s = ss;
  69. line->len = (uint32_t)len;
  70. smartlist_add(lst, line);
  71. }
  72. /** Compute the digest of <b>cons</b>, and store the result in
  73. * <b>digest_out</b>. Return 0 on success, -1 on failure. */
  74. /* This is a separate, mockable function so that we can override it when
  75. * fuzzing. */
  76. MOCK_IMPL(STATIC int,
  77. consensus_compute_digest,(const char *cons,
  78. consensus_digest_t *digest_out))
  79. {
  80. int r = crypto_digest256((char*)digest_out->sha3_256,
  81. cons, strlen(cons), DIGEST_SHA3_256);
  82. return r;
  83. }
  84. /** Return true iff <b>d1</b> and <b>d2</b> contain the same digest */
  85. /* This is a separate, mockable function so that we can override it when
  86. * fuzzing. */
  87. MOCK_IMPL(STATIC int,
  88. consensus_digest_eq,(const uint8_t *d1,
  89. const uint8_t *d2))
  90. {
  91. return fast_memeq(d1, d2, DIGEST256_LEN);
  92. }
  93. /** Create (allocate) a new slice from a smartlist. Assumes that the start
  94. * and the end indexes are within the bounds of the initial smartlist. The end
  95. * element is not part of the resulting slice. If end is -1, the slice is to
  96. * reach the end of the smartlist.
  97. */
  98. STATIC smartlist_slice_t *
  99. smartlist_slice(const smartlist_t *list, int start, int end)
  100. {
  101. int list_len = smartlist_len(list);
  102. tor_assert(start >= 0);
  103. tor_assert(start <= list_len);
  104. if (end == -1) {
  105. end = list_len;
  106. }
  107. tor_assert(start <= end);
  108. smartlist_slice_t *slice = tor_malloc(sizeof(smartlist_slice_t));
  109. slice->list = list;
  110. slice->offset = start;
  111. slice->len = end - start;
  112. return slice;
  113. }
  114. /** Helper: Compute the longest common subsequence lengths for the two slices.
  115. * Used as part of the diff generation to find the column at which to split
  116. * slice2 while still having the optimal solution.
  117. * If direction is -1, the navigation is reversed. Otherwise it must be 1.
  118. * The length of the resulting integer array is that of the second slice plus
  119. * one.
  120. */
  121. STATIC int *
  122. lcs_lengths(const smartlist_slice_t *slice1, const smartlist_slice_t *slice2,
  123. int direction)
  124. {
  125. size_t a_size = sizeof(int) * (slice2->len+1);
  126. /* Resulting lcs lengths. */
  127. int *result = tor_malloc_zero(a_size);
  128. /* Copy of the lcs lengths from the last iteration. */
  129. int *prev = tor_malloc(a_size);
  130. tor_assert(direction == 1 || direction == -1);
  131. int si = slice1->offset;
  132. if (direction == -1) {
  133. si += (slice1->len-1);
  134. }
  135. for (int i = 0; i < slice1->len; ++i, si+=direction) {
  136. const cdline_t *line1 = smartlist_get(slice1->list, si);
  137. /* Store the last results. */
  138. memcpy(prev, result, a_size);
  139. int sj = slice2->offset;
  140. if (direction == -1) {
  141. sj += (slice2->len-1);
  142. }
  143. for (int j = 0; j < slice2->len; ++j, sj+=direction) {
  144. const cdline_t *line2 = smartlist_get(slice2->list, sj);
  145. if (lines_eq(line1, line2)) {
  146. /* If the lines are equal, the lcs is one line longer. */
  147. result[j + 1] = prev[j] + 1;
  148. } else {
  149. /* If not, see what lcs parent path is longer. */
  150. result[j + 1] = MAX(result[j], prev[j + 1]);
  151. }
  152. }
  153. }
  154. tor_free(prev);
  155. return result;
  156. }
  157. /** Helper: Trim any number of lines that are equally at the start or the end
  158. * of both slices.
  159. */
  160. STATIC void
  161. trim_slices(smartlist_slice_t *slice1, smartlist_slice_t *slice2)
  162. {
  163. while (slice1->len>0 && slice2->len>0) {
  164. const cdline_t *line1 = smartlist_get(slice1->list, slice1->offset);
  165. const cdline_t *line2 = smartlist_get(slice2->list, slice2->offset);
  166. if (!lines_eq(line1, line2)) {
  167. break;
  168. }
  169. slice1->offset++; slice1->len--;
  170. slice2->offset++; slice2->len--;
  171. }
  172. int i1 = (slice1->offset+slice1->len)-1;
  173. int i2 = (slice2->offset+slice2->len)-1;
  174. while (slice1->len>0 && slice2->len>0) {
  175. const cdline_t *line1 = smartlist_get(slice1->list, i1);
  176. const cdline_t *line2 = smartlist_get(slice2->list, i2);
  177. if (!lines_eq(line1, line2)) {
  178. break;
  179. }
  180. i1--;
  181. slice1->len--;
  182. i2--;
  183. slice2->len--;
  184. }
  185. }
  186. /** Like smartlist_string_pos, but uses a cdline_t, and is restricted to the
  187. * bounds of the slice.
  188. */
  189. STATIC int
  190. smartlist_slice_string_pos(const smartlist_slice_t *slice,
  191. const cdline_t *string)
  192. {
  193. int end = slice->offset + slice->len;
  194. for (int i = slice->offset; i < end; ++i) {
  195. const cdline_t *el = smartlist_get(slice->list, i);
  196. if (lines_eq(el, string)) {
  197. return i;
  198. }
  199. }
  200. return -1;
  201. }
  202. /** Helper: Set all the appropriate changed booleans to true. The first slice
  203. * must be of length 0 or 1. All the lines of slice1 and slice2 which are not
  204. * present in the other slice will be set to changed in their bool array.
  205. * The two changed bool arrays are passed in the same order as the slices.
  206. */
  207. STATIC void
  208. set_changed(bitarray_t *changed1, bitarray_t *changed2,
  209. const smartlist_slice_t *slice1, const smartlist_slice_t *slice2)
  210. {
  211. int toskip = -1;
  212. tor_assert(slice1->len == 0 || slice1->len == 1);
  213. if (slice1->len == 1) {
  214. const cdline_t *line_common = smartlist_get(slice1->list, slice1->offset);
  215. toskip = smartlist_slice_string_pos(slice2, line_common);
  216. if (toskip == -1) {
  217. bitarray_set(changed1, slice1->offset);
  218. }
  219. }
  220. int end = slice2->offset + slice2->len;
  221. for (int i = slice2->offset; i < end; ++i) {
  222. if (i != toskip) {
  223. bitarray_set(changed2, i);
  224. }
  225. }
  226. }
  227. /*
  228. * Helper: Given that slice1 has been split by half into top and bot, we want
  229. * to fetch the column at which to split slice2 so that we are still on track
  230. * to the optimal diff solution, i.e. the shortest one. We use lcs_lengths
  231. * since the shortest diff is just another way to say the longest common
  232. * subsequence.
  233. */
  234. static int
  235. optimal_column_to_split(const smartlist_slice_t *top,
  236. const smartlist_slice_t *bot,
  237. const smartlist_slice_t *slice2)
  238. {
  239. int *lens_top = lcs_lengths(top, slice2, 1);
  240. int *lens_bot = lcs_lengths(bot, slice2, -1);
  241. int column=0, max_sum=-1;
  242. for (int i = 0; i < slice2->len+1; ++i) {
  243. int sum = lens_top[i] + lens_bot[slice2->len-i];
  244. if (sum > max_sum) {
  245. column = i;
  246. max_sum = sum;
  247. }
  248. }
  249. tor_free(lens_top);
  250. tor_free(lens_bot);
  251. return column;
  252. }
  253. /**
  254. * Helper: Figure out what elements are new or gone on the second smartlist
  255. * relative to the first smartlist, and store the booleans in the bitarrays.
  256. * True on the first bitarray means the element is gone, true on the second
  257. * bitarray means it's new.
  258. *
  259. * In its base case, either of the smartlists is of length <= 1 and we can
  260. * quickly see what elements are new or are gone. In the other case, we will
  261. * split one smartlist by half and we'll use optimal_column_to_split to find
  262. * the optimal column at which to split the second smartlist so that we are
  263. * finding the smallest diff possible.
  264. */
  265. STATIC void
  266. calc_changes(smartlist_slice_t *slice1,
  267. smartlist_slice_t *slice2,
  268. bitarray_t *changed1, bitarray_t *changed2)
  269. {
  270. trim_slices(slice1, slice2);
  271. if (slice1->len <= 1) {
  272. set_changed(changed1, changed2, slice1, slice2);
  273. } else if (slice2->len <= 1) {
  274. set_changed(changed2, changed1, slice2, slice1);
  275. /* Keep on splitting the slices in two. */
  276. } else {
  277. smartlist_slice_t *top, *bot, *left, *right;
  278. /* Split the first slice in half. */
  279. int mid = slice1->len/2;
  280. top = smartlist_slice(slice1->list, slice1->offset, slice1->offset+mid);
  281. bot = smartlist_slice(slice1->list, slice1->offset+mid,
  282. slice1->offset+slice1->len);
  283. /* Split the second slice by the optimal column. */
  284. int mid2 = optimal_column_to_split(top, bot, slice2);
  285. left = smartlist_slice(slice2->list, slice2->offset, slice2->offset+mid2);
  286. right = smartlist_slice(slice2->list, slice2->offset+mid2,
  287. slice2->offset+slice2->len);
  288. calc_changes(top, left, changed1, changed2);
  289. calc_changes(bot, right, changed1, changed2);
  290. tor_free(top);
  291. tor_free(bot);
  292. tor_free(left);
  293. tor_free(right);
  294. }
  295. }
  296. /* This table is from crypto.c. The SP and PAD defines are different. */
  297. #define NOT_VALID_BASE64 255
  298. #define X NOT_VALID_BASE64
  299. #define SP NOT_VALID_BASE64
  300. #define PAD NOT_VALID_BASE64
  301. static const uint8_t base64_compare_table[256] = {
  302. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X,
  303. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  304. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  305. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  306. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  307. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  308. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  309. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  310. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  311. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  312. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  313. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  314. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  315. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  316. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  317. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  318. };
  319. /** Helper: Get the identity hash from a router line, assuming that the line
  320. * at least appears to be a router line and thus starts with "r ".
  321. *
  322. * If an identity hash is found, store it (without decoding it) in
  323. * <b>hash_out</b>, and return 0. On failure, return -1.
  324. */
  325. STATIC int
  326. get_id_hash(const cdline_t *line, cdline_t *hash_out)
  327. {
  328. if (line->len < 2)
  329. return -1;
  330. /* Skip the router name. */
  331. const char *hash = memchr(line->s + 2, ' ', line->len - 2);
  332. if (!hash) {
  333. return -1;
  334. }
  335. hash++;
  336. const char *hash_end = hash;
  337. /* Stop when the first non-base64 character is found. Use unsigned chars to
  338. * avoid negative indexes causing crashes.
  339. */
  340. while (base64_compare_table[*((unsigned char*)hash_end)]
  341. != NOT_VALID_BASE64 &&
  342. hash_end < line->s + line->len) {
  343. hash_end++;
  344. }
  345. /* Empty hash. */
  346. if (hash_end == hash) {
  347. return -1;
  348. }
  349. hash_out->s = hash;
  350. /* Always true because lines are limited to this length */
  351. tor_assert(hash_end - hash <= UINT32_MAX);
  352. hash_out->len = (uint32_t)(hash_end - hash);
  353. return 0;
  354. }
  355. /** Helper: Check that a line is a valid router entry. We must at least be
  356. * able to fetch a proper identity hash from it for it to be valid.
  357. */
  358. STATIC int
  359. is_valid_router_entry(const cdline_t *line)
  360. {
  361. if (line->len < 2 || fast_memneq(line->s, "r ", 2))
  362. return 0;
  363. cdline_t tmp;
  364. return (get_id_hash(line, &tmp) == 0);
  365. }
  366. /** Helper: Find the next router line starting at the current position.
  367. * Assumes that cur is lower than the length of the smartlist, i.e. it is a
  368. * line within the bounds of the consensus. The only exception is when we
  369. * don't want to skip the first line, in which case cur will be -1.
  370. */
  371. STATIC int
  372. next_router(const smartlist_t *cons, int cur)
  373. {
  374. int len = smartlist_len(cons);
  375. tor_assert(cur >= -1 && cur < len);
  376. if (++cur >= len) {
  377. return len;
  378. }
  379. const cdline_t *line = smartlist_get(cons, cur);
  380. while (!is_valid_router_entry(line)) {
  381. if (++cur >= len) {
  382. return len;
  383. }
  384. line = smartlist_get(cons, cur);
  385. }
  386. return cur;
  387. }
  388. /** Helper: compare two base64-encoded identity hashes, which may be of
  389. * different lengths. Comparison ends when the first non-base64 char is found.
  390. */
  391. STATIC int
  392. base64cmp(const cdline_t *hash1, const cdline_t *hash2)
  393. {
  394. /* NULL is always lower, useful for last_hash which starts at NULL. */
  395. if (!hash1->s && !hash2->s) {
  396. return 0;
  397. }
  398. if (!hash1->s) {
  399. return -1;
  400. }
  401. if (!hash2->s) {
  402. return 1;
  403. }
  404. /* Don't index with a char; char may be signed. */
  405. const unsigned char *a = (unsigned char*)hash1->s;
  406. const unsigned char *b = (unsigned char*)hash2->s;
  407. const unsigned char *a_end = a + hash1->len;
  408. const unsigned char *b_end = b + hash2->len;
  409. while (1) {
  410. uint8_t av = base64_compare_table[*a];
  411. uint8_t bv = base64_compare_table[*b];
  412. if (av == NOT_VALID_BASE64) {
  413. if (bv == NOT_VALID_BASE64) {
  414. /* Both ended with exactly the same characters. */
  415. return 0;
  416. } else {
  417. /* hash2 goes on longer than hash1 and thus hash1 is lower. */
  418. return -1;
  419. }
  420. } else if (bv == NOT_VALID_BASE64) {
  421. /* hash1 goes on longer than hash2 and thus hash1 is greater. */
  422. return 1;
  423. } else if (av < bv) {
  424. /* The first difference shows that hash1 is lower. */
  425. return -1;
  426. } else if (av > bv) {
  427. /* The first difference shows that hash1 is greater. */
  428. return 1;
  429. } else {
  430. a++;
  431. b++;
  432. if (a == a_end) {
  433. if (b == b_end) {
  434. return 0;
  435. } else {
  436. return -1;
  437. }
  438. } else if (b == b_end) {
  439. return 1;
  440. }
  441. }
  442. }
  443. }
  444. /** Generate an ed diff as a smartlist from two consensuses, also given as
  445. * smartlists. Will return NULL if the diff could not be generated, which can
  446. * happen if any lines the script had to add matched "." or if the routers
  447. * were not properly ordered.
  448. *
  449. * All cdline_t objects in the resulting object are either references to lines
  450. * in one of the inputs, or are newly allocated lines in the provided memarea.
  451. *
  452. * This implementation is consensus-specific. To generate an ed diff for any
  453. * given input in quadratic time, you can replace all the code until the
  454. * navigation in reverse order with the following:
  455. *
  456. * int len1 = smartlist_len(cons1);
  457. * int len2 = smartlist_len(cons2);
  458. * bitarray_t *changed1 = bitarray_init_zero(len1);
  459. * bitarray_t *changed2 = bitarray_init_zero(len2);
  460. * cons1_sl = smartlist_slice(cons1, 0, -1);
  461. * cons2_sl = smartlist_slice(cons2, 0, -1);
  462. * calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  463. */
  464. STATIC smartlist_t *
  465. gen_ed_diff(const smartlist_t *cons1, const smartlist_t *cons2,
  466. memarea_t *area)
  467. {
  468. int len1 = smartlist_len(cons1);
  469. int len2 = smartlist_len(cons2);
  470. smartlist_t *result = smartlist_new();
  471. /* Initialize the changed bitarrays to zero, so that calc_changes only needs
  472. * to set the ones that matter and leave the rest untouched.
  473. */
  474. bitarray_t *changed1 = bitarray_init_zero(len1);
  475. bitarray_t *changed2 = bitarray_init_zero(len2);
  476. int i1=-1, i2=-1;
  477. int start1=0, start2=0;
  478. /* To check that hashes are ordered properly */
  479. cdline_t hash1 = { NULL, 0 }, hash2 = { NULL, 0 };
  480. cdline_t last_hash1 = { NULL, 0 }, last_hash2 = { NULL, 0 };
  481. /* i1 and i2 are initialized at the first line of each consensus. They never
  482. * reach past len1 and len2 respectively, since next_router doesn't let that
  483. * happen. i1 and i2 are advanced by at least one line at each iteration as
  484. * long as they have not yet reached len1 and len2, so the loop is
  485. * guaranteed to end, and each pair of (i1,i2) will be inspected at most
  486. * once.
  487. */
  488. while (i1 < len1 || i2 < len2) {
  489. /* Advance each of the two navigation positions by one router entry if not
  490. * yet at the end.
  491. */
  492. if (i1 < len1) {
  493. i1 = next_router(cons1, i1);
  494. if (i1 != len1) {
  495. memcpy(&last_hash1, &hash1, sizeof(cdline_t));
  496. if (get_id_hash(smartlist_get(cons1, i1), &hash1) < 0 ||
  497. base64cmp(&hash1, &last_hash1) <= 0) {
  498. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  499. "the base consensus doesn't have its router entries "
  500. "sorted properly.");
  501. goto error_cleanup;
  502. }
  503. }
  504. }
  505. if (i2 < len2) {
  506. i2 = next_router(cons2, i2);
  507. if (i2 != len2) {
  508. memcpy(&last_hash2, &hash2, sizeof(cdline_t));
  509. if (get_id_hash(smartlist_get(cons2, i2), &hash2) < 0 ||
  510. base64cmp(&hash2, &last_hash2) <= 0) {
  511. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  512. "the target consensus doesn't have its router entries "
  513. "sorted properly.");
  514. goto error_cleanup;
  515. }
  516. }
  517. }
  518. /* If we have reached the end of both consensuses, there is no need to
  519. * compare hashes anymore, since this is the last iteration.
  520. */
  521. if (i1 < len1 || i2 < len2) {
  522. /* Keep on advancing the lower (by identity hash sorting) position until
  523. * we have two matching positions. The only other possible outcome is
  524. * that a lower position reaches the end of the consensus before it can
  525. * reach a hash that is no longer the lower one. Since there will always
  526. * be a lower hash for as long as the loop runs, one of the two indexes
  527. * will always be incremented, thus assuring that the loop must end
  528. * after a finite number of iterations. If that cannot be because said
  529. * consensus has already reached the end, both are extended to their
  530. * respecting ends since we are done.
  531. */
  532. int cmp = base64cmp(&hash1, &hash2);
  533. while (cmp != 0) {
  534. if (i1 < len1 && cmp < 0) {
  535. i1 = next_router(cons1, i1);
  536. if (i1 == len1) {
  537. /* We finished the first consensus, so grab all the remaining
  538. * lines of the second consensus and finish up.
  539. */
  540. i2 = len2;
  541. break;
  542. }
  543. memcpy(&last_hash1, &hash1, sizeof(cdline_t));
  544. if (get_id_hash(smartlist_get(cons1, i1), &hash1) < 0 ||
  545. base64cmp(&hash1, &last_hash1) <= 0) {
  546. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff "
  547. "because the base consensus doesn't have its router entries "
  548. "sorted properly.");
  549. goto error_cleanup;
  550. }
  551. } else if (i2 < len2 && cmp > 0) {
  552. i2 = next_router(cons2, i2);
  553. if (i2 == len2) {
  554. /* We finished the second consensus, so grab all the remaining
  555. * lines of the first consensus and finish up.
  556. */
  557. i1 = len1;
  558. break;
  559. }
  560. memcpy(&last_hash2, &hash2, sizeof(cdline_t));
  561. if (get_id_hash(smartlist_get(cons2, i2), &hash2) < 0 ||
  562. base64cmp(&hash2, &last_hash2) <= 0) {
  563. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff "
  564. "because the target consensus doesn't have its router entries "
  565. "sorted properly.");
  566. goto error_cleanup;
  567. }
  568. } else {
  569. i1 = len1;
  570. i2 = len2;
  571. break;
  572. }
  573. cmp = base64cmp(&hash1, &hash2);
  574. }
  575. }
  576. /* Make slices out of these chunks (up to the common router entry) and
  577. * calculate the changes for them.
  578. * Error if any of the two slices are longer than 10K lines. That should
  579. * never happen with any pair of real consensuses. Feeding more than 10K
  580. * lines to calc_changes would be very slow anyway.
  581. */
  582. #define MAX_LINE_COUNT (10000)
  583. if (i1-start1 > MAX_LINE_COUNT || i2-start2 > MAX_LINE_COUNT) {
  584. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  585. "we found too few common router ids.");
  586. goto error_cleanup;
  587. }
  588. smartlist_slice_t *cons1_sl = smartlist_slice(cons1, start1, i1);
  589. smartlist_slice_t *cons2_sl = smartlist_slice(cons2, start2, i2);
  590. calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  591. tor_free(cons1_sl);
  592. tor_free(cons2_sl);
  593. start1 = i1, start2 = i2;
  594. }
  595. /* Navigate the changes in reverse order and generate one ed command for
  596. * each chunk of changes.
  597. */
  598. i1=len1-1, i2=len2-1;
  599. char buf[128];
  600. while (i1 > 0 || i2 > 0) {
  601. int start1x, start2x, end1, end2, added, deleted;
  602. /* We are at a point were no changed bools are true, so just keep going. */
  603. if (!(i1 >= 0 && bitarray_is_set(changed1, i1)) &&
  604. !(i2 >= 0 && bitarray_is_set(changed2, i2))) {
  605. if (i1 >= 0) {
  606. i1--;
  607. }
  608. if (i2 >= 0) {
  609. i2--;
  610. }
  611. continue;
  612. }
  613. end1 = i1, end2 = i2;
  614. /* Grab all contiguous changed lines */
  615. while (i1 >= 0 && bitarray_is_set(changed1, i1)) {
  616. i1--;
  617. }
  618. while (i2 >= 0 && bitarray_is_set(changed2, i2)) {
  619. i2--;
  620. }
  621. start1x = i1+1, start2x = i2+1;
  622. added = end2-i2, deleted = end1-i1;
  623. if (added == 0) {
  624. if (deleted == 1) {
  625. tor_snprintf(buf, sizeof(buf), "%id", start1x+1);
  626. smartlist_add_linecpy(result, area, buf);
  627. } else {
  628. tor_snprintf(buf, sizeof(buf), "%i,%id", start1x+1, start1x+deleted);
  629. smartlist_add_linecpy(result, area, buf);
  630. }
  631. } else {
  632. int i;
  633. if (deleted == 0) {
  634. tor_snprintf(buf, sizeof(buf), "%ia", start1x);
  635. smartlist_add_linecpy(result, area, buf);
  636. } else if (deleted == 1) {
  637. tor_snprintf(buf, sizeof(buf), "%ic", start1x+1);
  638. smartlist_add_linecpy(result, area, buf);
  639. } else {
  640. tor_snprintf(buf, sizeof(buf), "%i,%ic", start1x+1, start1x+deleted);
  641. smartlist_add_linecpy(result, area, buf);
  642. }
  643. for (i = start2x; i <= end2; ++i) {
  644. cdline_t *line = smartlist_get(cons2, i);
  645. if (line_str_eq(line, ".")) {
  646. log_warn(LD_CONSDIFF, "Cannot generate consensus diff because "
  647. "one of the lines to be added is \".\".");
  648. goto error_cleanup;
  649. }
  650. smartlist_add(result, line);
  651. }
  652. smartlist_add_linecpy(result, area, ".");
  653. }
  654. }
  655. bitarray_free(changed1);
  656. bitarray_free(changed2);
  657. return result;
  658. error_cleanup:
  659. bitarray_free(changed1);
  660. bitarray_free(changed2);
  661. smartlist_free(result);
  662. return NULL;
  663. }
  664. /** Apply the ed diff, starting at <b>diff_starting_line</b>, to the consensus
  665. * and return a new consensus, also as a line-based smartlist. Will return
  666. * NULL if the ed diff is not properly formatted.
  667. *
  668. * All cdline_t objects in the resulting object are references to lines
  669. * in one of the inputs; nothing is copied.
  670. */
  671. STATIC smartlist_t *
  672. apply_ed_diff(const smartlist_t *cons1, const smartlist_t *diff,
  673. int diff_starting_line)
  674. {
  675. int diff_len = smartlist_len(diff);
  676. int j = smartlist_len(cons1);
  677. smartlist_t *cons2 = smartlist_new();
  678. for (int i=diff_starting_line; i<diff_len; ++i) {
  679. const cdline_t *diff_cdline = smartlist_get(diff, i);
  680. char diff_line[128];
  681. char *endptr1, *endptr2;
  682. if (diff_cdline->len > sizeof(diff_line) - 1) {
  683. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  684. "an ed command was far too long");
  685. goto error_cleanup;
  686. }
  687. memcpy(diff_line, diff_cdline->s, diff_cdline->len);
  688. diff_line[diff_cdline->len] = 0;
  689. int start = (int)strtol(diff_line, &endptr1, 10);
  690. int end;
  691. if (endptr1 == diff_line) {
  692. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  693. "an ed command was missing a line number.");
  694. goto error_cleanup;
  695. }
  696. /* Two-item range */
  697. if (*endptr1 == ',') {
  698. end = (int)strtol(endptr1+1, &endptr2, 10);
  699. if (endptr2 == endptr1+1) {
  700. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  701. "an ed command was missing a range end line number.");
  702. goto error_cleanup;
  703. }
  704. /* Incoherent range. */
  705. if (end <= start) {
  706. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  707. "an invalid range was found in an ed command.");
  708. goto error_cleanup;
  709. }
  710. /* We'll take <n1> as <n1>,<n1> for simplicity. */
  711. } else {
  712. endptr2 = endptr1;
  713. end = start;
  714. }
  715. if (end > j) {
  716. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  717. "its commands are not properly sorted in reverse order.");
  718. goto error_cleanup;
  719. }
  720. if (*endptr2 == '\0') {
  721. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  722. "a line with no ed command was found");
  723. goto error_cleanup;
  724. }
  725. if (*(endptr2+1) != '\0') {
  726. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  727. "an ed command longer than one char was found.");
  728. goto error_cleanup;
  729. }
  730. char action = *endptr2;
  731. switch (action) {
  732. case 'a':
  733. case 'c':
  734. case 'd':
  735. break;
  736. default:
  737. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  738. "an unrecognised ed command was found.");
  739. goto error_cleanup;
  740. }
  741. /* Add unchanged lines. */
  742. for (; j && j > end; --j) {
  743. cdline_t *cons_line = smartlist_get(cons1, j-1);
  744. smartlist_add(cons2, cons_line);
  745. }
  746. /* Ignore removed lines. */
  747. if (action == 'c' || action == 'd') {
  748. while (--j >= start) {
  749. /* Skip line */
  750. }
  751. }
  752. /* Add new lines in reverse order, since it will all be reversed at the
  753. * end.
  754. */
  755. if (action == 'a' || action == 'c') {
  756. int added_end = i;
  757. i++; /* Skip the line with the range and command. */
  758. while (i < diff_len) {
  759. if (line_str_eq(smartlist_get(diff, i), ".")) {
  760. break;
  761. }
  762. if (++i == diff_len) {
  763. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  764. "it has lines to be inserted that don't end with a \".\".");
  765. goto error_cleanup;
  766. }
  767. }
  768. int added_i = i-1;
  769. /* It would make no sense to add zero new lines. */
  770. if (added_i == added_end) {
  771. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  772. "it has an ed command that tries to insert zero lines.");
  773. goto error_cleanup;
  774. }
  775. while (added_i > added_end) {
  776. cdline_t *added_line = smartlist_get(diff, added_i--);
  777. smartlist_add(cons2, added_line);
  778. }
  779. }
  780. }
  781. /* Add remaining unchanged lines. */
  782. for (; j > 0; --j) {
  783. cdline_t *cons_line = smartlist_get(cons1, j-1);
  784. smartlist_add(cons2, cons_line);
  785. }
  786. /* Reverse the whole thing since we did it from the end. */
  787. smartlist_reverse(cons2);
  788. return cons2;
  789. error_cleanup:
  790. smartlist_free(cons2);
  791. return NULL;
  792. }
  793. /** Generate a consensus diff as a smartlist from two given consensuses, also
  794. * as smartlists. Will return NULL if the consensus diff could not be
  795. * generated. Neither of the two consensuses are modified in any way, so it's
  796. * up to the caller to free their resources.
  797. */
  798. smartlist_t *
  799. consdiff_gen_diff(const smartlist_t *cons1,
  800. const smartlist_t *cons2,
  801. const consensus_digest_t *digests1,
  802. const consensus_digest_t *digests2,
  803. memarea_t *area)
  804. {
  805. smartlist_t *ed_diff = gen_ed_diff(cons1, cons2, area);
  806. /* ed diff could not be generated - reason already logged by gen_ed_diff. */
  807. if (!ed_diff) {
  808. goto error_cleanup;
  809. }
  810. /* See that the script actually produces what we want. */
  811. smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff, 0);
  812. if (!ed_cons2) {
  813. /* LCOV_EXCL_START -- impossible if diff generation is correct */
  814. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  815. "the generated ed diff could not be tested to successfully generate "
  816. "the target consensus.");
  817. goto error_cleanup;
  818. /* LCOV_EXCL_STOP */
  819. }
  820. int cons2_eq = 1;
  821. if (smartlist_len(cons2) == smartlist_len(ed_cons2)) {
  822. SMARTLIST_FOREACH_BEGIN(cons2, const cdline_t *, line1) {
  823. const cdline_t *line2 = smartlist_get(ed_cons2, line1_sl_idx);
  824. if (! lines_eq(line1, line2) ) {
  825. cons2_eq = 0;
  826. break;
  827. }
  828. } SMARTLIST_FOREACH_END(line1);
  829. } else {
  830. cons2_eq = 0;
  831. }
  832. smartlist_free(ed_cons2);
  833. if (!cons2_eq) {
  834. /* LCOV_EXCL_START -- impossible if diff generation is correct. */
  835. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  836. "the generated ed diff did not generate the target consensus "
  837. "successfully when tested.");
  838. goto error_cleanup;
  839. /* LCOV_EXCL_STOP */
  840. }
  841. char cons1_hash_hex[HEX_DIGEST256_LEN+1];
  842. char cons2_hash_hex[HEX_DIGEST256_LEN+1];
  843. base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
  844. (const char*)digests1->sha3_256, DIGEST256_LEN);
  845. base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
  846. (const char*)digests2->sha3_256, DIGEST256_LEN);
  847. /* Create the resulting consensus diff. */
  848. char buf[160];
  849. smartlist_t *result = smartlist_new();
  850. tor_snprintf(buf, sizeof(buf), "%s", ns_diff_version);
  851. smartlist_add_linecpy(result, area, buf);
  852. tor_snprintf(buf, sizeof(buf), "%s %s %s", hash_token,
  853. cons1_hash_hex, cons2_hash_hex);
  854. smartlist_add_linecpy(result, area, buf);
  855. smartlist_add_all(result, ed_diff);
  856. smartlist_free(ed_diff);
  857. return result;
  858. error_cleanup:
  859. if (ed_diff) {
  860. /* LCOV_EXCL_START -- ed_diff is NULL except in unreachable cases above */
  861. smartlist_free(ed_diff);
  862. /* LCOV_EXCL_STOP */
  863. }
  864. return NULL;
  865. }
  866. /** Fetch the digest of the base consensus in the consensus diff, encoded in
  867. * base16 as found in the diff itself. digest1_out and digest2_out must be of
  868. * length DIGEST256_LEN or larger if not NULL.
  869. */
  870. int
  871. consdiff_get_digests(const smartlist_t *diff,
  872. char *digest1_out,
  873. char *digest2_out)
  874. {
  875. smartlist_t *hash_words = NULL;
  876. const cdline_t *format;
  877. char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
  878. char *cons1_hash_hex, *cons2_hash_hex;
  879. if (smartlist_len(diff) < 2) {
  880. log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
  881. goto error_cleanup;
  882. }
  883. /* Check that it's the format and version we know. */
  884. format = smartlist_get(diff, 0);
  885. if (!line_str_eq(format, ns_diff_version)) {
  886. log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
  887. goto error_cleanup;
  888. }
  889. /* Grab the base16 digests. */
  890. hash_words = smartlist_new();
  891. {
  892. const cdline_t *line2 = smartlist_get(diff, 1);
  893. char *h = tor_memdup_nulterm(line2->s, line2->len);
  894. smartlist_split_string(hash_words, h, " ", 0, 0);
  895. tor_free(h);
  896. }
  897. /* There have to be three words, the first of which must be hash_token. */
  898. if (smartlist_len(hash_words) != 3 ||
  899. strcmp(smartlist_get(hash_words, 0), hash_token)) {
  900. log_info(LD_CONSDIFF, "The provided consensus diff does not include "
  901. "the necessary digests.");
  902. goto error_cleanup;
  903. }
  904. /* Expected hashes as found in the consensus diff header. They must be of
  905. * length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
  906. * If any of the decodings fail, error to make sure that the hashes are
  907. * proper base16-encoded digests.
  908. */
  909. cons1_hash_hex = smartlist_get(hash_words, 1);
  910. cons2_hash_hex = smartlist_get(hash_words, 2);
  911. if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
  912. strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
  913. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  914. "base16-encoded digests of incorrect size.");
  915. goto error_cleanup;
  916. }
  917. if (base16_decode(cons1_hash, DIGEST256_LEN,
  918. cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
  919. base16_decode(cons2_hash, DIGEST256_LEN,
  920. cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
  921. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  922. "malformed digests.");
  923. goto error_cleanup;
  924. }
  925. if (digest1_out) {
  926. memcpy(digest1_out, cons1_hash, DIGEST256_LEN);
  927. }
  928. if (digest2_out) {
  929. memcpy(digest2_out, cons2_hash, DIGEST256_LEN);
  930. }
  931. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  932. smartlist_free(hash_words);
  933. return 0;
  934. error_cleanup:
  935. if (hash_words) {
  936. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  937. smartlist_free(hash_words);
  938. }
  939. return 1;
  940. }
  941. /** Apply the consensus diff to the given consensus and return a new
  942. * consensus, also as a line-based smartlist. Will return NULL if the diff
  943. * could not be applied. Neither the consensus nor the diff are modified in
  944. * any way, so it's up to the caller to free their resources.
  945. */
  946. char *
  947. consdiff_apply_diff(const smartlist_t *cons1,
  948. const smartlist_t *diff,
  949. const consensus_digest_t *digests1)
  950. {
  951. smartlist_t *cons2 = NULL;
  952. char *cons2_str = NULL;
  953. char e_cons1_hash[DIGEST256_LEN];
  954. char e_cons2_hash[DIGEST256_LEN];
  955. if (consdiff_get_digests(diff, e_cons1_hash, e_cons2_hash) != 0) {
  956. goto error_cleanup;
  957. }
  958. /* See that the consensus that was given to us matches its hash. */
  959. if (!consensus_digest_eq(digests1->sha3_256,
  960. (const uint8_t*)e_cons1_hash)) {
  961. char hex_digest1[HEX_DIGEST256_LEN+1];
  962. char e_hex_digest1[HEX_DIGEST256_LEN+1];
  963. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  964. "the base consensus doesn't match the digest as found in "
  965. "the consensus diff header.");
  966. base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
  967. (const char *)digests1->sha3_256, DIGEST256_LEN);
  968. base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
  969. e_cons1_hash, DIGEST256_LEN);
  970. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  971. hex_digest1, e_hex_digest1);
  972. goto error_cleanup;
  973. }
  974. /* Grab the ed diff and calculate the resulting consensus. */
  975. /* Skip the first two lines. */
  976. cons2 = apply_ed_diff(cons1, diff, 2);
  977. /* ed diff could not be applied - reason already logged by apply_ed_diff. */
  978. if (!cons2) {
  979. goto error_cleanup;
  980. }
  981. cons2_str = consensus_join_lines(cons2);
  982. consensus_digest_t cons2_digests;
  983. if (consensus_compute_digest(cons2_str, &cons2_digests) < 0) {
  984. /* LCOV_EXCL_START -- digest can't fail */
  985. log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
  986. "resulting from applying a consensus diff.");
  987. goto error_cleanup;
  988. /* LCOV_EXCL_STOP */
  989. }
  990. /* See that the resulting consensus matches its hash. */
  991. if (!consensus_digest_eq(cons2_digests.sha3_256,
  992. (const uint8_t*)e_cons2_hash)) {
  993. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  994. "the resulting consensus doesn't match the digest as found in "
  995. "the consensus diff header.");
  996. char hex_digest2[HEX_DIGEST256_LEN+1];
  997. char e_hex_digest2[HEX_DIGEST256_LEN+1];
  998. base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
  999. (const char *)cons2_digests.sha3_256, DIGEST256_LEN);
  1000. base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
  1001. e_cons2_hash, DIGEST256_LEN);
  1002. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  1003. hex_digest2, e_hex_digest2);
  1004. goto error_cleanup;
  1005. }
  1006. goto done;
  1007. error_cleanup:
  1008. tor_free(cons2_str); /* Sets it to NULL */
  1009. done:
  1010. if (cons2) {
  1011. smartlist_free(cons2);
  1012. }
  1013. return cons2_str;
  1014. }
  1015. /**
  1016. * Helper: For every NL-terminated line in <b>s</b>, add a cdline referring to
  1017. * that line (without trailing newline) to <b>out</b>. Return -1 if there are
  1018. * any non-NL terminated lines; 0 otherwise.
  1019. *
  1020. * Unlike tor_split_lines, this function avoids ambiguity on its
  1021. * handling of a final line that isn't NL-terminated.
  1022. *
  1023. * All cdline_t objects are allocated in the provided memarea. Strings
  1024. * are not copied: if <b>s</b> changes or becomes invalid, then all
  1025. * generated cdlines will become invalid.
  1026. */
  1027. STATIC int
  1028. consensus_split_lines(smartlist_t *out, const char *s, memarea_t *area)
  1029. {
  1030. while (*s) {
  1031. const char *eol = strchr(s, '\n');
  1032. if (!eol) {
  1033. /* File doesn't end with newline. */
  1034. return -1;
  1035. }
  1036. if (eol - s > UINT32_MAX) {
  1037. /* Line is far too long. */
  1038. return -1;
  1039. }
  1040. cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
  1041. line->s = s;
  1042. line->len = (uint32_t)(eol - s);
  1043. smartlist_add(out, line);
  1044. s = eol+1;
  1045. }
  1046. return 0;
  1047. }
  1048. /** Given a list of cdline_t, return a newly allocated string containing
  1049. * all of the lines, terminated with NL, concatenated.
  1050. *
  1051. * Unlike smartlist_join_strings(), avoids lossy operations on empty
  1052. * lists. */
  1053. static char *
  1054. consensus_join_lines(const smartlist_t *inp)
  1055. {
  1056. size_t n = 0;
  1057. SMARTLIST_FOREACH(inp, const cdline_t *, cdline, n += cdline->len + 1);
  1058. n += 1;
  1059. char *result = tor_malloc(n);
  1060. char *out = result;
  1061. SMARTLIST_FOREACH_BEGIN(inp, const cdline_t *, cdline) {
  1062. memcpy(out, cdline->s, cdline->len);
  1063. out += cdline->len;
  1064. *out++ = '\n';
  1065. } SMARTLIST_FOREACH_END(cdline);
  1066. *out++ = '\0';
  1067. tor_assert(out == result+n);
  1068. return result;
  1069. }
  1070. /** Given two consensus documents, try to compute a diff between them. On
  1071. * success, retun a newly allocated string containing that diff. On failure,
  1072. * return NULL. */
  1073. char *
  1074. consensus_diff_generate(const char *cons1,
  1075. const char *cons2)
  1076. {
  1077. consensus_digest_t d1, d2;
  1078. smartlist_t *lines1 = NULL, *lines2 = NULL, *result_lines = NULL;
  1079. int r1, r2;
  1080. char *result = NULL;
  1081. r1 = consensus_compute_digest(cons1, &d1);
  1082. r2 = consensus_compute_digest(cons2, &d2);
  1083. if (BUG(r1 < 0 || r2 < 0))
  1084. return NULL; // LCOV_EXCL_LINE
  1085. memarea_t *area = memarea_new();
  1086. lines1 = smartlist_new();
  1087. lines2 = smartlist_new();
  1088. if (consensus_split_lines(lines1, cons1, area) < 0)
  1089. goto done;
  1090. if (consensus_split_lines(lines2, cons2, area) < 0)
  1091. goto done;
  1092. result_lines = consdiff_gen_diff(lines1, lines2, &d1, &d2, area);
  1093. done:
  1094. if (result_lines) {
  1095. result = consensus_join_lines(result_lines);
  1096. smartlist_free(result_lines);
  1097. }
  1098. memarea_drop_all(area);
  1099. smartlist_free(lines1);
  1100. smartlist_free(lines2);
  1101. return result;
  1102. }
  1103. /** Given a consensus document and a diff, try to apply the diff to the
  1104. * consensus. On success return a newly allocated string containing the new
  1105. * consensus. On failure, return NULL. */
  1106. char *
  1107. consensus_diff_apply(const char *consensus,
  1108. const char *diff)
  1109. {
  1110. consensus_digest_t d1;
  1111. smartlist_t *lines1 = NULL, *lines2 = NULL;
  1112. int r1;
  1113. char *result = NULL;
  1114. memarea_t *area = memarea_new();
  1115. r1 = consensus_compute_digest(consensus, &d1);
  1116. if (BUG(r1 < 0))
  1117. return NULL; // LCOV_EXCL_LINE
  1118. lines1 = smartlist_new();
  1119. lines2 = smartlist_new();
  1120. if (consensus_split_lines(lines1, consensus, area) < 0)
  1121. goto done;
  1122. if (consensus_split_lines(lines2, diff, area) < 0)
  1123. goto done;
  1124. result = consdiff_apply_diff(lines1, lines2, &d1);
  1125. done:
  1126. smartlist_free(lines1);
  1127. smartlist_free(lines2);
  1128. memarea_drop_all(area);
  1129. return result;
  1130. }