consdiff.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  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. /** Structure used to remember the previous and current identity hash of
  445. * the "r " lines in a consensus, to enforce well-ordering. */
  446. typedef struct router_id_iterator_t {
  447. cdline_t last_hash;
  448. cdline_t hash;
  449. } router_id_iterator_t;
  450. /**
  451. * Initializer for a router_id_iterator_t.
  452. */
  453. #define ROUTER_ID_ITERATOR_INIT { { NULL, 0 }, { NULL, 0 } }
  454. /** Given an index *<b>idxp</b> into the consensus at <b>cons</b>, advance
  455. * the index to the next router line ("r ...") in the consensus, or to
  456. * an index one after the end of the list if there is no such line.
  457. *
  458. * Use <b>iter</b> to record the hash of the found router line, if any,
  459. * and to enforce ordering on the hashes. If the hashes are mis-ordered,
  460. * return -1. Else, return 0.
  461. **/
  462. static int
  463. find_next_router_line(const smartlist_t *cons,
  464. const char *consname,
  465. int *idxp,
  466. router_id_iterator_t *iter)
  467. {
  468. *idxp = next_router(cons, *idxp);
  469. if (*idxp < smartlist_len(cons)) {
  470. memcpy(&iter->last_hash, &iter->hash, sizeof(cdline_t));
  471. if (get_id_hash(smartlist_get(cons, *idxp), &iter->hash) < 0 ||
  472. base64cmp(&iter->hash, &iter->last_hash) <= 0) {
  473. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  474. "the %s consensus doesn't have its router entries sorted "
  475. "properly.", consname);
  476. return -1;
  477. }
  478. }
  479. return 0;
  480. }
  481. /** Generate an ed diff as a smartlist from two consensuses, also given as
  482. * smartlists. Will return NULL if the diff could not be generated, which can
  483. * happen if any lines the script had to add matched "." or if the routers
  484. * were not properly ordered.
  485. *
  486. * All cdline_t objects in the resulting object are either references to lines
  487. * in one of the inputs, or are newly allocated lines in the provided memarea.
  488. *
  489. * This implementation is consensus-specific. To generate an ed diff for any
  490. * given input in quadratic time, you can replace all the code until the
  491. * navigation in reverse order with the following:
  492. *
  493. * int len1 = smartlist_len(cons1);
  494. * int len2 = smartlist_len(cons2);
  495. * bitarray_t *changed1 = bitarray_init_zero(len1);
  496. * bitarray_t *changed2 = bitarray_init_zero(len2);
  497. * cons1_sl = smartlist_slice(cons1, 0, -1);
  498. * cons2_sl = smartlist_slice(cons2, 0, -1);
  499. * calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  500. */
  501. STATIC smartlist_t *
  502. gen_ed_diff(const smartlist_t *cons1, const smartlist_t *cons2,
  503. memarea_t *area)
  504. {
  505. int len1 = smartlist_len(cons1);
  506. int len2 = smartlist_len(cons2);
  507. smartlist_t *result = smartlist_new();
  508. /* Initialize the changed bitarrays to zero, so that calc_changes only needs
  509. * to set the ones that matter and leave the rest untouched.
  510. */
  511. bitarray_t *changed1 = bitarray_init_zero(len1);
  512. bitarray_t *changed2 = bitarray_init_zero(len2);
  513. int i1=-1, i2=-1;
  514. int start1=0, start2=0;
  515. /* To check that hashes are ordered properly */
  516. router_id_iterator_t iter1 = ROUTER_ID_ITERATOR_INIT;
  517. router_id_iterator_t iter2 = ROUTER_ID_ITERATOR_INIT;
  518. /* i1 and i2 are initialized at the first line of each consensus. They never
  519. * reach past len1 and len2 respectively, since next_router doesn't let that
  520. * happen. i1 and i2 are advanced by at least one line at each iteration as
  521. * long as they have not yet reached len1 and len2, so the loop is
  522. * guaranteed to end, and each pair of (i1,i2) will be inspected at most
  523. * once.
  524. */
  525. while (i1 < len1 || i2 < len2) {
  526. /* Advance each of the two navigation positions by one router entry if not
  527. * yet at the end.
  528. */
  529. if (i1 < len1) {
  530. if (find_next_router_line(cons1, "base", &i1, &iter1) < 0) {
  531. goto error_cleanup;
  532. }
  533. }
  534. if (i2 < len2) {
  535. if (find_next_router_line(cons2, "target", &i2, &iter2) < 0) {
  536. goto error_cleanup;
  537. }
  538. }
  539. /* If we have reached the end of both consensuses, there is no need to
  540. * compare hashes anymore, since this is the last iteration.
  541. */
  542. if (i1 < len1 || i2 < len2) {
  543. /* Keep on advancing the lower (by identity hash sorting) position until
  544. * we have two matching positions. The only other possible outcome is
  545. * that a lower position reaches the end of the consensus before it can
  546. * reach a hash that is no longer the lower one. Since there will always
  547. * be a lower hash for as long as the loop runs, one of the two indexes
  548. * will always be incremented, thus assuring that the loop must end
  549. * after a finite number of iterations. If that cannot be because said
  550. * consensus has already reached the end, both are extended to their
  551. * respecting ends since we are done.
  552. */
  553. int cmp = base64cmp(&iter1.hash, &iter2.hash);
  554. while (cmp != 0) {
  555. if (i1 < len1 && cmp < 0) {
  556. if (find_next_router_line(cons1, "base", &i1, &iter1) < 0) {
  557. goto error_cleanup;
  558. }
  559. if (i1 == len1) {
  560. /* We finished the first consensus, so grab all the remaining
  561. * lines of the second consensus and finish up.
  562. */
  563. i2 = len2;
  564. break;
  565. }
  566. } else if (i2 < len2 && cmp > 0) {
  567. if (find_next_router_line(cons2, "target", &i2, &iter2) < 0) {
  568. goto error_cleanup;
  569. }
  570. if (i2 == len2) {
  571. /* We finished the second consensus, so grab all the remaining
  572. * lines of the first consensus and finish up.
  573. */
  574. i1 = len1;
  575. break;
  576. }
  577. } else {
  578. i1 = len1;
  579. i2 = len2;
  580. break;
  581. }
  582. cmp = base64cmp(&iter1.hash, &iter2.hash);
  583. }
  584. }
  585. /* Make slices out of these chunks (up to the common router entry) and
  586. * calculate the changes for them.
  587. * Error if any of the two slices are longer than 10K lines. That should
  588. * never happen with any pair of real consensuses. Feeding more than 10K
  589. * lines to calc_changes would be very slow anyway.
  590. */
  591. #define MAX_LINE_COUNT (10000)
  592. if (i1-start1 > MAX_LINE_COUNT || i2-start2 > MAX_LINE_COUNT) {
  593. log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
  594. "we found too few common router ids.");
  595. goto error_cleanup;
  596. }
  597. smartlist_slice_t *cons1_sl = smartlist_slice(cons1, start1, i1);
  598. smartlist_slice_t *cons2_sl = smartlist_slice(cons2, start2, i2);
  599. calc_changes(cons1_sl, cons2_sl, changed1, changed2);
  600. tor_free(cons1_sl);
  601. tor_free(cons2_sl);
  602. start1 = i1, start2 = i2;
  603. }
  604. /* Navigate the changes in reverse order and generate one ed command for
  605. * each chunk of changes.
  606. */
  607. i1=len1-1, i2=len2-1;
  608. char buf[128];
  609. while (i1 > 0 || i2 > 0) {
  610. int start1x, start2x, end1, end2, added, deleted;
  611. /* We are at a point were no changed bools are true, so just keep going. */
  612. if (!(i1 >= 0 && bitarray_is_set(changed1, i1)) &&
  613. !(i2 >= 0 && bitarray_is_set(changed2, i2))) {
  614. if (i1 >= 0) {
  615. i1--;
  616. }
  617. if (i2 >= 0) {
  618. i2--;
  619. }
  620. continue;
  621. }
  622. end1 = i1, end2 = i2;
  623. /* Grab all contiguous changed lines */
  624. while (i1 >= 0 && bitarray_is_set(changed1, i1)) {
  625. i1--;
  626. }
  627. while (i2 >= 0 && bitarray_is_set(changed2, i2)) {
  628. i2--;
  629. }
  630. start1x = i1+1, start2x = i2+1;
  631. added = end2-i2, deleted = end1-i1;
  632. if (added == 0) {
  633. if (deleted == 1) {
  634. tor_snprintf(buf, sizeof(buf), "%id", start1x+1);
  635. smartlist_add_linecpy(result, area, buf);
  636. } else {
  637. tor_snprintf(buf, sizeof(buf), "%i,%id", start1x+1, start1x+deleted);
  638. smartlist_add_linecpy(result, area, buf);
  639. }
  640. } else {
  641. int i;
  642. if (deleted == 0) {
  643. tor_snprintf(buf, sizeof(buf), "%ia", start1x);
  644. smartlist_add_linecpy(result, area, buf);
  645. } else if (deleted == 1) {
  646. tor_snprintf(buf, sizeof(buf), "%ic", start1x+1);
  647. smartlist_add_linecpy(result, area, buf);
  648. } else {
  649. tor_snprintf(buf, sizeof(buf), "%i,%ic", start1x+1, start1x+deleted);
  650. smartlist_add_linecpy(result, area, buf);
  651. }
  652. for (i = start2x; i <= end2; ++i) {
  653. cdline_t *line = smartlist_get(cons2, i);
  654. if (line_str_eq(line, ".")) {
  655. log_warn(LD_CONSDIFF, "Cannot generate consensus diff because "
  656. "one of the lines to be added is \".\".");
  657. goto error_cleanup;
  658. }
  659. smartlist_add(result, line);
  660. }
  661. smartlist_add_linecpy(result, area, ".");
  662. }
  663. }
  664. bitarray_free(changed1);
  665. bitarray_free(changed2);
  666. return result;
  667. error_cleanup:
  668. bitarray_free(changed1);
  669. bitarray_free(changed2);
  670. smartlist_free(result);
  671. return NULL;
  672. }
  673. /* Helper: Read a base-10 number between 0 and INT32_MAX from <b>s</b> and
  674. * store it in <b>num_out</b>. Advance <b>s</b> to the characer immediately
  675. * after the number. Return 0 on success, -1 on failure. */
  676. static int
  677. get_linenum(const char **s, int *num_out)
  678. {
  679. int ok;
  680. char *next;
  681. *num_out = (int) tor_parse_long(*s, 10, 0, INT32_MAX, &ok, &next);
  682. if (ok && next) {
  683. *s = next;
  684. return 0;
  685. } else {
  686. return -1;
  687. }
  688. }
  689. /** Apply the ed diff, starting at <b>diff_starting_line</b>, to the consensus
  690. * and return a new consensus, also as a line-based smartlist. Will return
  691. * NULL if the ed diff is not properly formatted.
  692. *
  693. * All cdline_t objects in the resulting object are references to lines
  694. * in one of the inputs; nothing is copied.
  695. */
  696. STATIC smartlist_t *
  697. apply_ed_diff(const smartlist_t *cons1, const smartlist_t *diff,
  698. int diff_starting_line)
  699. {
  700. int diff_len = smartlist_len(diff);
  701. int j = smartlist_len(cons1);
  702. smartlist_t *cons2 = smartlist_new();
  703. for (int i=diff_starting_line; i<diff_len; ++i) {
  704. const cdline_t *diff_cdline = smartlist_get(diff, i);
  705. char diff_line[128];
  706. if (diff_cdline->len > sizeof(diff_line) - 1) {
  707. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  708. "an ed command was far too long");
  709. goto error_cleanup;
  710. }
  711. /* Copy the line to make it nul-terminated. */
  712. memcpy(diff_line, diff_cdline->s, diff_cdline->len);
  713. diff_line[diff_cdline->len] = 0;
  714. const char *ptr = diff_line;
  715. int start = 0, end = 0;
  716. if (get_linenum(&ptr, &start) < 0) {
  717. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  718. "an ed command was missing a line number.");
  719. goto error_cleanup;
  720. }
  721. if (*ptr == ',') {
  722. /* Two-item range */
  723. ++ptr;
  724. if (get_linenum(&ptr, &end) < 0) {
  725. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  726. "an ed command was missing a range end line number.");
  727. goto error_cleanup;
  728. }
  729. /* Incoherent range. */
  730. if (end <= start) {
  731. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  732. "an invalid range was found in an ed command.");
  733. goto error_cleanup;
  734. }
  735. } else {
  736. /* We'll take <n1> as <n1>,<n1> for simplicity. */
  737. end = start;
  738. }
  739. if (end > j) {
  740. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  741. "its commands are not properly sorted in reverse order.");
  742. goto error_cleanup;
  743. }
  744. if (*ptr == '\0') {
  745. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  746. "a line with no ed command was found");
  747. goto error_cleanup;
  748. }
  749. if (*(ptr+1) != '\0') {
  750. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  751. "an ed command longer than one char was found.");
  752. goto error_cleanup;
  753. }
  754. char action = *ptr;
  755. switch (action) {
  756. case 'a':
  757. case 'c':
  758. case 'd':
  759. break;
  760. default:
  761. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  762. "an unrecognised ed command was found.");
  763. goto error_cleanup;
  764. }
  765. /* Add unchanged lines. */
  766. for (; j && j > end; --j) {
  767. cdline_t *cons_line = smartlist_get(cons1, j-1);
  768. smartlist_add(cons2, cons_line);
  769. }
  770. /* Ignore removed lines. */
  771. if (action == 'c' || action == 'd') {
  772. while (--j >= start) {
  773. /* Skip line */
  774. }
  775. }
  776. /* Add new lines in reverse order, since it will all be reversed at the
  777. * end.
  778. */
  779. if (action == 'a' || action == 'c') {
  780. int added_end = i;
  781. i++; /* Skip the line with the range and command. */
  782. while (i < diff_len) {
  783. if (line_str_eq(smartlist_get(diff, i), ".")) {
  784. break;
  785. }
  786. if (++i == diff_len) {
  787. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  788. "it has lines to be inserted that don't end with a \".\".");
  789. goto error_cleanup;
  790. }
  791. }
  792. int added_i = i-1;
  793. /* It would make no sense to add zero new lines. */
  794. if (added_i == added_end) {
  795. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  796. "it has an ed command that tries to insert zero lines.");
  797. goto error_cleanup;
  798. }
  799. while (added_i > added_end) {
  800. cdline_t *added_line = smartlist_get(diff, added_i--);
  801. smartlist_add(cons2, added_line);
  802. }
  803. }
  804. }
  805. /* Add remaining unchanged lines. */
  806. for (; j > 0; --j) {
  807. cdline_t *cons_line = smartlist_get(cons1, j-1);
  808. smartlist_add(cons2, cons_line);
  809. }
  810. /* Reverse the whole thing since we did it from the end. */
  811. smartlist_reverse(cons2);
  812. return cons2;
  813. error_cleanup:
  814. smartlist_free(cons2);
  815. return NULL;
  816. }
  817. /** Generate a consensus diff as a smartlist from two given consensuses, also
  818. * as smartlists. Will return NULL if the consensus diff could not be
  819. * generated. Neither of the two consensuses are modified in any way, so it's
  820. * up to the caller to free their resources.
  821. */
  822. smartlist_t *
  823. consdiff_gen_diff(const smartlist_t *cons1,
  824. const smartlist_t *cons2,
  825. const consensus_digest_t *digests1,
  826. const consensus_digest_t *digests2,
  827. memarea_t *area)
  828. {
  829. smartlist_t *ed_diff = gen_ed_diff(cons1, cons2, area);
  830. /* ed diff could not be generated - reason already logged by gen_ed_diff. */
  831. if (!ed_diff) {
  832. goto error_cleanup;
  833. }
  834. /* See that the script actually produces what we want. */
  835. smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff, 0);
  836. if (!ed_cons2) {
  837. /* LCOV_EXCL_START -- impossible if diff generation is correct */
  838. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  839. "the generated ed diff could not be tested to successfully generate "
  840. "the target consensus.");
  841. goto error_cleanup;
  842. /* LCOV_EXCL_STOP */
  843. }
  844. int cons2_eq = 1;
  845. if (smartlist_len(cons2) == smartlist_len(ed_cons2)) {
  846. SMARTLIST_FOREACH_BEGIN(cons2, const cdline_t *, line1) {
  847. const cdline_t *line2 = smartlist_get(ed_cons2, line1_sl_idx);
  848. if (! lines_eq(line1, line2) ) {
  849. cons2_eq = 0;
  850. break;
  851. }
  852. } SMARTLIST_FOREACH_END(line1);
  853. } else {
  854. cons2_eq = 0;
  855. }
  856. smartlist_free(ed_cons2);
  857. if (!cons2_eq) {
  858. /* LCOV_EXCL_START -- impossible if diff generation is correct. */
  859. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  860. "the generated ed diff did not generate the target consensus "
  861. "successfully when tested.");
  862. goto error_cleanup;
  863. /* LCOV_EXCL_STOP */
  864. }
  865. char cons1_hash_hex[HEX_DIGEST256_LEN+1];
  866. char cons2_hash_hex[HEX_DIGEST256_LEN+1];
  867. base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
  868. (const char*)digests1->sha3_256, DIGEST256_LEN);
  869. base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
  870. (const char*)digests2->sha3_256, DIGEST256_LEN);
  871. /* Create the resulting consensus diff. */
  872. char buf[160];
  873. smartlist_t *result = smartlist_new();
  874. tor_snprintf(buf, sizeof(buf), "%s", ns_diff_version);
  875. smartlist_add_linecpy(result, area, buf);
  876. tor_snprintf(buf, sizeof(buf), "%s %s %s", hash_token,
  877. cons1_hash_hex, cons2_hash_hex);
  878. smartlist_add_linecpy(result, area, buf);
  879. smartlist_add_all(result, ed_diff);
  880. smartlist_free(ed_diff);
  881. return result;
  882. error_cleanup:
  883. if (ed_diff) {
  884. /* LCOV_EXCL_START -- ed_diff is NULL except in unreachable cases above */
  885. smartlist_free(ed_diff);
  886. /* LCOV_EXCL_STOP */
  887. }
  888. return NULL;
  889. }
  890. /** Fetch the digest of the base consensus in the consensus diff, encoded in
  891. * base16 as found in the diff itself. digest1_out and digest2_out must be of
  892. * length DIGEST256_LEN or larger if not NULL.
  893. */
  894. int
  895. consdiff_get_digests(const smartlist_t *diff,
  896. char *digest1_out,
  897. char *digest2_out)
  898. {
  899. smartlist_t *hash_words = NULL;
  900. const cdline_t *format;
  901. char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
  902. char *cons1_hash_hex, *cons2_hash_hex;
  903. if (smartlist_len(diff) < 2) {
  904. log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
  905. goto error_cleanup;
  906. }
  907. /* Check that it's the format and version we know. */
  908. format = smartlist_get(diff, 0);
  909. if (!line_str_eq(format, ns_diff_version)) {
  910. log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
  911. goto error_cleanup;
  912. }
  913. /* Grab the base16 digests. */
  914. hash_words = smartlist_new();
  915. {
  916. const cdline_t *line2 = smartlist_get(diff, 1);
  917. char *h = tor_memdup_nulterm(line2->s, line2->len);
  918. smartlist_split_string(hash_words, h, " ", 0, 0);
  919. tor_free(h);
  920. }
  921. /* There have to be three words, the first of which must be hash_token. */
  922. if (smartlist_len(hash_words) != 3 ||
  923. strcmp(smartlist_get(hash_words, 0), hash_token)) {
  924. log_info(LD_CONSDIFF, "The provided consensus diff does not include "
  925. "the necessary digests.");
  926. goto error_cleanup;
  927. }
  928. /* Expected hashes as found in the consensus diff header. They must be of
  929. * length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
  930. * If any of the decodings fail, error to make sure that the hashes are
  931. * proper base16-encoded digests.
  932. */
  933. cons1_hash_hex = smartlist_get(hash_words, 1);
  934. cons2_hash_hex = smartlist_get(hash_words, 2);
  935. if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
  936. strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
  937. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  938. "base16-encoded digests of incorrect size.");
  939. goto error_cleanup;
  940. }
  941. if (base16_decode(cons1_hash, DIGEST256_LEN,
  942. cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
  943. base16_decode(cons2_hash, DIGEST256_LEN,
  944. cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
  945. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  946. "malformed digests.");
  947. goto error_cleanup;
  948. }
  949. if (digest1_out) {
  950. memcpy(digest1_out, cons1_hash, DIGEST256_LEN);
  951. }
  952. if (digest2_out) {
  953. memcpy(digest2_out, cons2_hash, DIGEST256_LEN);
  954. }
  955. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  956. smartlist_free(hash_words);
  957. return 0;
  958. error_cleanup:
  959. if (hash_words) {
  960. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  961. smartlist_free(hash_words);
  962. }
  963. return 1;
  964. }
  965. /** Apply the consensus diff to the given consensus and return a new
  966. * consensus, also as a line-based smartlist. Will return NULL if the diff
  967. * could not be applied. Neither the consensus nor the diff are modified in
  968. * any way, so it's up to the caller to free their resources.
  969. */
  970. char *
  971. consdiff_apply_diff(const smartlist_t *cons1,
  972. const smartlist_t *diff,
  973. const consensus_digest_t *digests1)
  974. {
  975. smartlist_t *cons2 = NULL;
  976. char *cons2_str = NULL;
  977. char e_cons1_hash[DIGEST256_LEN];
  978. char e_cons2_hash[DIGEST256_LEN];
  979. if (consdiff_get_digests(diff, e_cons1_hash, e_cons2_hash) != 0) {
  980. goto error_cleanup;
  981. }
  982. /* See that the consensus that was given to us matches its hash. */
  983. if (!consensus_digest_eq(digests1->sha3_256,
  984. (const uint8_t*)e_cons1_hash)) {
  985. char hex_digest1[HEX_DIGEST256_LEN+1];
  986. char e_hex_digest1[HEX_DIGEST256_LEN+1];
  987. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  988. "the base consensus doesn't match the digest as found in "
  989. "the consensus diff header.");
  990. base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
  991. (const char *)digests1->sha3_256, DIGEST256_LEN);
  992. base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
  993. e_cons1_hash, DIGEST256_LEN);
  994. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  995. hex_digest1, e_hex_digest1);
  996. goto error_cleanup;
  997. }
  998. /* Grab the ed diff and calculate the resulting consensus. */
  999. /* Skip the first two lines. */
  1000. cons2 = apply_ed_diff(cons1, diff, 2);
  1001. /* ed diff could not be applied - reason already logged by apply_ed_diff. */
  1002. if (!cons2) {
  1003. goto error_cleanup;
  1004. }
  1005. cons2_str = consensus_join_lines(cons2);
  1006. consensus_digest_t cons2_digests;
  1007. if (consensus_compute_digest(cons2_str, &cons2_digests) < 0) {
  1008. /* LCOV_EXCL_START -- digest can't fail */
  1009. log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
  1010. "resulting from applying a consensus diff.");
  1011. goto error_cleanup;
  1012. /* LCOV_EXCL_STOP */
  1013. }
  1014. /* See that the resulting consensus matches its hash. */
  1015. if (!consensus_digest_eq(cons2_digests.sha3_256,
  1016. (const uint8_t*)e_cons2_hash)) {
  1017. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  1018. "the resulting consensus doesn't match the digest as found in "
  1019. "the consensus diff header.");
  1020. char hex_digest2[HEX_DIGEST256_LEN+1];
  1021. char e_hex_digest2[HEX_DIGEST256_LEN+1];
  1022. base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
  1023. (const char *)cons2_digests.sha3_256, DIGEST256_LEN);
  1024. base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
  1025. e_cons2_hash, DIGEST256_LEN);
  1026. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  1027. hex_digest2, e_hex_digest2);
  1028. goto error_cleanup;
  1029. }
  1030. goto done;
  1031. error_cleanup:
  1032. tor_free(cons2_str); /* Sets it to NULL */
  1033. done:
  1034. if (cons2) {
  1035. smartlist_free(cons2);
  1036. }
  1037. return cons2_str;
  1038. }
  1039. /** Any consensus line longer than this means that the input is invalid. */
  1040. #define CONSENSUS_LINE_MAX_LEN (1<<20)
  1041. /**
  1042. * Helper: For every NL-terminated line in <b>s</b>, add a cdline referring to
  1043. * that line (without trailing newline) to <b>out</b>. Return -1 if there are
  1044. * any non-NL terminated lines; 0 otherwise.
  1045. *
  1046. * Unlike tor_split_lines, this function avoids ambiguity on its
  1047. * handling of a final line that isn't NL-terminated.
  1048. *
  1049. * All cdline_t objects are allocated in the provided memarea. Strings
  1050. * are not copied: if <b>s</b> changes or becomes invalid, then all
  1051. * generated cdlines will become invalid.
  1052. */
  1053. STATIC int
  1054. consensus_split_lines(smartlist_t *out, const char *s, memarea_t *area)
  1055. {
  1056. while (*s) {
  1057. const char *eol = strchr(s, '\n');
  1058. if (!eol) {
  1059. /* File doesn't end with newline. */
  1060. return -1;
  1061. }
  1062. if (eol - s > CONSENSUS_LINE_MAX_LEN) {
  1063. /* Line is far too long. */
  1064. return -1;
  1065. }
  1066. cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
  1067. line->s = s;
  1068. line->len = (uint32_t)(eol - s);
  1069. smartlist_add(out, line);
  1070. s = eol+1;
  1071. }
  1072. return 0;
  1073. }
  1074. /** Given a list of cdline_t, return a newly allocated string containing
  1075. * all of the lines, terminated with NL, concatenated.
  1076. *
  1077. * Unlike smartlist_join_strings(), avoids lossy operations on empty
  1078. * lists. */
  1079. static char *
  1080. consensus_join_lines(const smartlist_t *inp)
  1081. {
  1082. size_t n = 0;
  1083. SMARTLIST_FOREACH(inp, const cdline_t *, cdline, n += cdline->len + 1);
  1084. n += 1;
  1085. char *result = tor_malloc(n);
  1086. char *out = result;
  1087. SMARTLIST_FOREACH_BEGIN(inp, const cdline_t *, cdline) {
  1088. memcpy(out, cdline->s, cdline->len);
  1089. out += cdline->len;
  1090. *out++ = '\n';
  1091. } SMARTLIST_FOREACH_END(cdline);
  1092. *out++ = '\0';
  1093. tor_assert(out == result+n);
  1094. return result;
  1095. }
  1096. /** Given two consensus documents, try to compute a diff between them. On
  1097. * success, retun a newly allocated string containing that diff. On failure,
  1098. * return NULL. */
  1099. char *
  1100. consensus_diff_generate(const char *cons1,
  1101. const char *cons2)
  1102. {
  1103. consensus_digest_t d1, d2;
  1104. smartlist_t *lines1 = NULL, *lines2 = NULL, *result_lines = NULL;
  1105. int r1, r2;
  1106. char *result = NULL;
  1107. r1 = consensus_compute_digest(cons1, &d1);
  1108. r2 = consensus_compute_digest(cons2, &d2);
  1109. if (BUG(r1 < 0 || r2 < 0))
  1110. return NULL; // LCOV_EXCL_LINE
  1111. memarea_t *area = memarea_new();
  1112. lines1 = smartlist_new();
  1113. lines2 = smartlist_new();
  1114. if (consensus_split_lines(lines1, cons1, area) < 0)
  1115. goto done;
  1116. if (consensus_split_lines(lines2, cons2, area) < 0)
  1117. goto done;
  1118. result_lines = consdiff_gen_diff(lines1, lines2, &d1, &d2, area);
  1119. done:
  1120. if (result_lines) {
  1121. result = consensus_join_lines(result_lines);
  1122. smartlist_free(result_lines);
  1123. }
  1124. memarea_drop_all(area);
  1125. smartlist_free(lines1);
  1126. smartlist_free(lines2);
  1127. return result;
  1128. }
  1129. /** Given a consensus document and a diff, try to apply the diff to the
  1130. * consensus. On success return a newly allocated string containing the new
  1131. * consensus. On failure, return NULL. */
  1132. char *
  1133. consensus_diff_apply(const char *consensus,
  1134. const char *diff)
  1135. {
  1136. consensus_digest_t d1;
  1137. smartlist_t *lines1 = NULL, *lines2 = NULL;
  1138. int r1;
  1139. char *result = NULL;
  1140. memarea_t *area = memarea_new();
  1141. r1 = consensus_compute_digest(consensus, &d1);
  1142. if (BUG(r1 < 0))
  1143. return NULL; // LCOV_EXCL_LINE
  1144. lines1 = smartlist_new();
  1145. lines2 = smartlist_new();
  1146. if (consensus_split_lines(lines1, consensus, area) < 0)
  1147. goto done;
  1148. if (consensus_split_lines(lines2, diff, area) < 0)
  1149. goto done;
  1150. result = consdiff_apply_diff(lines1, lines2, &d1);
  1151. done:
  1152. smartlist_free(lines1);
  1153. smartlist_free(lines2);
  1154. memarea_drop_all(area);
  1155. return result;
  1156. }