consdiff.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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. /** Apply the ed diff, starting at <b>diff_starting_line</b>, to the consensus
  674. * and return a new consensus, also as a line-based smartlist. Will return
  675. * NULL if the ed diff is not properly formatted.
  676. *
  677. * All cdline_t objects in the resulting object are references to lines
  678. * in one of the inputs; nothing is copied.
  679. */
  680. STATIC smartlist_t *
  681. apply_ed_diff(const smartlist_t *cons1, const smartlist_t *diff,
  682. int diff_starting_line)
  683. {
  684. int diff_len = smartlist_len(diff);
  685. int j = smartlist_len(cons1);
  686. smartlist_t *cons2 = smartlist_new();
  687. for (int i=diff_starting_line; i<diff_len; ++i) {
  688. const cdline_t *diff_cdline = smartlist_get(diff, i);
  689. char diff_line[128];
  690. char *endptr1, *endptr2;
  691. if (diff_cdline->len > sizeof(diff_line) - 1) {
  692. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  693. "an ed command was far too long");
  694. goto error_cleanup;
  695. }
  696. memcpy(diff_line, diff_cdline->s, diff_cdline->len);
  697. diff_line[diff_cdline->len] = 0;
  698. int start = (int)strtol(diff_line, &endptr1, 10);
  699. int end;
  700. if (endptr1 == diff_line) {
  701. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  702. "an ed command was missing a line number.");
  703. goto error_cleanup;
  704. }
  705. /* Two-item range */
  706. if (*endptr1 == ',') {
  707. end = (int)strtol(endptr1+1, &endptr2, 10);
  708. if (endptr2 == endptr1+1) {
  709. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  710. "an ed command was missing a range end line number.");
  711. goto error_cleanup;
  712. }
  713. /* Incoherent range. */
  714. if (end <= start) {
  715. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  716. "an invalid range was found in an ed command.");
  717. goto error_cleanup;
  718. }
  719. /* We'll take <n1> as <n1>,<n1> for simplicity. */
  720. } else {
  721. endptr2 = endptr1;
  722. end = start;
  723. }
  724. if (end > j) {
  725. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  726. "its commands are not properly sorted in reverse order.");
  727. goto error_cleanup;
  728. }
  729. if (*endptr2 == '\0') {
  730. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  731. "a line with no ed command was found");
  732. goto error_cleanup;
  733. }
  734. if (*(endptr2+1) != '\0') {
  735. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  736. "an ed command longer than one char was found.");
  737. goto error_cleanup;
  738. }
  739. char action = *endptr2;
  740. switch (action) {
  741. case 'a':
  742. case 'c':
  743. case 'd':
  744. break;
  745. default:
  746. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  747. "an unrecognised ed command was found.");
  748. goto error_cleanup;
  749. }
  750. /* Add unchanged lines. */
  751. for (; j && j > end; --j) {
  752. cdline_t *cons_line = smartlist_get(cons1, j-1);
  753. smartlist_add(cons2, cons_line);
  754. }
  755. /* Ignore removed lines. */
  756. if (action == 'c' || action == 'd') {
  757. while (--j >= start) {
  758. /* Skip line */
  759. }
  760. }
  761. /* Add new lines in reverse order, since it will all be reversed at the
  762. * end.
  763. */
  764. if (action == 'a' || action == 'c') {
  765. int added_end = i;
  766. i++; /* Skip the line with the range and command. */
  767. while (i < diff_len) {
  768. if (line_str_eq(smartlist_get(diff, i), ".")) {
  769. break;
  770. }
  771. if (++i == diff_len) {
  772. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  773. "it has lines to be inserted that don't end with a \".\".");
  774. goto error_cleanup;
  775. }
  776. }
  777. int added_i = i-1;
  778. /* It would make no sense to add zero new lines. */
  779. if (added_i == added_end) {
  780. log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
  781. "it has an ed command that tries to insert zero lines.");
  782. goto error_cleanup;
  783. }
  784. while (added_i > added_end) {
  785. cdline_t *added_line = smartlist_get(diff, added_i--);
  786. smartlist_add(cons2, added_line);
  787. }
  788. }
  789. }
  790. /* Add remaining unchanged lines. */
  791. for (; j > 0; --j) {
  792. cdline_t *cons_line = smartlist_get(cons1, j-1);
  793. smartlist_add(cons2, cons_line);
  794. }
  795. /* Reverse the whole thing since we did it from the end. */
  796. smartlist_reverse(cons2);
  797. return cons2;
  798. error_cleanup:
  799. smartlist_free(cons2);
  800. return NULL;
  801. }
  802. /** Generate a consensus diff as a smartlist from two given consensuses, also
  803. * as smartlists. Will return NULL if the consensus diff could not be
  804. * generated. Neither of the two consensuses are modified in any way, so it's
  805. * up to the caller to free their resources.
  806. */
  807. smartlist_t *
  808. consdiff_gen_diff(const smartlist_t *cons1,
  809. const smartlist_t *cons2,
  810. const consensus_digest_t *digests1,
  811. const consensus_digest_t *digests2,
  812. memarea_t *area)
  813. {
  814. smartlist_t *ed_diff = gen_ed_diff(cons1, cons2, area);
  815. /* ed diff could not be generated - reason already logged by gen_ed_diff. */
  816. if (!ed_diff) {
  817. goto error_cleanup;
  818. }
  819. /* See that the script actually produces what we want. */
  820. smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff, 0);
  821. if (!ed_cons2) {
  822. /* LCOV_EXCL_START -- impossible if diff generation is correct */
  823. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  824. "the generated ed diff could not be tested to successfully generate "
  825. "the target consensus.");
  826. goto error_cleanup;
  827. /* LCOV_EXCL_STOP */
  828. }
  829. int cons2_eq = 1;
  830. if (smartlist_len(cons2) == smartlist_len(ed_cons2)) {
  831. SMARTLIST_FOREACH_BEGIN(cons2, const cdline_t *, line1) {
  832. const cdline_t *line2 = smartlist_get(ed_cons2, line1_sl_idx);
  833. if (! lines_eq(line1, line2) ) {
  834. cons2_eq = 0;
  835. break;
  836. }
  837. } SMARTLIST_FOREACH_END(line1);
  838. } else {
  839. cons2_eq = 0;
  840. }
  841. smartlist_free(ed_cons2);
  842. if (!cons2_eq) {
  843. /* LCOV_EXCL_START -- impossible if diff generation is correct. */
  844. log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
  845. "the generated ed diff did not generate the target consensus "
  846. "successfully when tested.");
  847. goto error_cleanup;
  848. /* LCOV_EXCL_STOP */
  849. }
  850. char cons1_hash_hex[HEX_DIGEST256_LEN+1];
  851. char cons2_hash_hex[HEX_DIGEST256_LEN+1];
  852. base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
  853. (const char*)digests1->sha3_256, DIGEST256_LEN);
  854. base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
  855. (const char*)digests2->sha3_256, DIGEST256_LEN);
  856. /* Create the resulting consensus diff. */
  857. char buf[160];
  858. smartlist_t *result = smartlist_new();
  859. tor_snprintf(buf, sizeof(buf), "%s", ns_diff_version);
  860. smartlist_add_linecpy(result, area, buf);
  861. tor_snprintf(buf, sizeof(buf), "%s %s %s", hash_token,
  862. cons1_hash_hex, cons2_hash_hex);
  863. smartlist_add_linecpy(result, area, buf);
  864. smartlist_add_all(result, ed_diff);
  865. smartlist_free(ed_diff);
  866. return result;
  867. error_cleanup:
  868. if (ed_diff) {
  869. /* LCOV_EXCL_START -- ed_diff is NULL except in unreachable cases above */
  870. smartlist_free(ed_diff);
  871. /* LCOV_EXCL_STOP */
  872. }
  873. return NULL;
  874. }
  875. /** Fetch the digest of the base consensus in the consensus diff, encoded in
  876. * base16 as found in the diff itself. digest1_out and digest2_out must be of
  877. * length DIGEST256_LEN or larger if not NULL.
  878. */
  879. int
  880. consdiff_get_digests(const smartlist_t *diff,
  881. char *digest1_out,
  882. char *digest2_out)
  883. {
  884. smartlist_t *hash_words = NULL;
  885. const cdline_t *format;
  886. char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
  887. char *cons1_hash_hex, *cons2_hash_hex;
  888. if (smartlist_len(diff) < 2) {
  889. log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
  890. goto error_cleanup;
  891. }
  892. /* Check that it's the format and version we know. */
  893. format = smartlist_get(diff, 0);
  894. if (!line_str_eq(format, ns_diff_version)) {
  895. log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
  896. goto error_cleanup;
  897. }
  898. /* Grab the base16 digests. */
  899. hash_words = smartlist_new();
  900. {
  901. const cdline_t *line2 = smartlist_get(diff, 1);
  902. char *h = tor_memdup_nulterm(line2->s, line2->len);
  903. smartlist_split_string(hash_words, h, " ", 0, 0);
  904. tor_free(h);
  905. }
  906. /* There have to be three words, the first of which must be hash_token. */
  907. if (smartlist_len(hash_words) != 3 ||
  908. strcmp(smartlist_get(hash_words, 0), hash_token)) {
  909. log_info(LD_CONSDIFF, "The provided consensus diff does not include "
  910. "the necessary digests.");
  911. goto error_cleanup;
  912. }
  913. /* Expected hashes as found in the consensus diff header. They must be of
  914. * length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
  915. * If any of the decodings fail, error to make sure that the hashes are
  916. * proper base16-encoded digests.
  917. */
  918. cons1_hash_hex = smartlist_get(hash_words, 1);
  919. cons2_hash_hex = smartlist_get(hash_words, 2);
  920. if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
  921. strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
  922. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  923. "base16-encoded digests of incorrect size.");
  924. goto error_cleanup;
  925. }
  926. if (base16_decode(cons1_hash, DIGEST256_LEN,
  927. cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
  928. base16_decode(cons2_hash, DIGEST256_LEN,
  929. cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
  930. log_info(LD_CONSDIFF, "The provided consensus diff includes "
  931. "malformed digests.");
  932. goto error_cleanup;
  933. }
  934. if (digest1_out) {
  935. memcpy(digest1_out, cons1_hash, DIGEST256_LEN);
  936. }
  937. if (digest2_out) {
  938. memcpy(digest2_out, cons2_hash, DIGEST256_LEN);
  939. }
  940. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  941. smartlist_free(hash_words);
  942. return 0;
  943. error_cleanup:
  944. if (hash_words) {
  945. SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
  946. smartlist_free(hash_words);
  947. }
  948. return 1;
  949. }
  950. /** Apply the consensus diff to the given consensus and return a new
  951. * consensus, also as a line-based smartlist. Will return NULL if the diff
  952. * could not be applied. Neither the consensus nor the diff are modified in
  953. * any way, so it's up to the caller to free their resources.
  954. */
  955. char *
  956. consdiff_apply_diff(const smartlist_t *cons1,
  957. const smartlist_t *diff,
  958. const consensus_digest_t *digests1)
  959. {
  960. smartlist_t *cons2 = NULL;
  961. char *cons2_str = NULL;
  962. char e_cons1_hash[DIGEST256_LEN];
  963. char e_cons2_hash[DIGEST256_LEN];
  964. if (consdiff_get_digests(diff, e_cons1_hash, e_cons2_hash) != 0) {
  965. goto error_cleanup;
  966. }
  967. /* See that the consensus that was given to us matches its hash. */
  968. if (!consensus_digest_eq(digests1->sha3_256,
  969. (const uint8_t*)e_cons1_hash)) {
  970. char hex_digest1[HEX_DIGEST256_LEN+1];
  971. char e_hex_digest1[HEX_DIGEST256_LEN+1];
  972. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  973. "the base consensus doesn't match the digest as found in "
  974. "the consensus diff header.");
  975. base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
  976. (const char *)digests1->sha3_256, DIGEST256_LEN);
  977. base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
  978. e_cons1_hash, DIGEST256_LEN);
  979. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  980. hex_digest1, e_hex_digest1);
  981. goto error_cleanup;
  982. }
  983. /* Grab the ed diff and calculate the resulting consensus. */
  984. /* Skip the first two lines. */
  985. cons2 = apply_ed_diff(cons1, diff, 2);
  986. /* ed diff could not be applied - reason already logged by apply_ed_diff. */
  987. if (!cons2) {
  988. goto error_cleanup;
  989. }
  990. cons2_str = consensus_join_lines(cons2);
  991. consensus_digest_t cons2_digests;
  992. if (consensus_compute_digest(cons2_str, &cons2_digests) < 0) {
  993. /* LCOV_EXCL_START -- digest can't fail */
  994. log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
  995. "resulting from applying a consensus diff.");
  996. goto error_cleanup;
  997. /* LCOV_EXCL_STOP */
  998. }
  999. /* See that the resulting consensus matches its hash. */
  1000. if (!consensus_digest_eq(cons2_digests.sha3_256,
  1001. (const uint8_t*)e_cons2_hash)) {
  1002. log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
  1003. "the resulting consensus doesn't match the digest as found in "
  1004. "the consensus diff header.");
  1005. char hex_digest2[HEX_DIGEST256_LEN+1];
  1006. char e_hex_digest2[HEX_DIGEST256_LEN+1];
  1007. base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
  1008. (const char *)cons2_digests.sha3_256, DIGEST256_LEN);
  1009. base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
  1010. e_cons2_hash, DIGEST256_LEN);
  1011. log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
  1012. hex_digest2, e_hex_digest2);
  1013. goto error_cleanup;
  1014. }
  1015. goto done;
  1016. error_cleanup:
  1017. tor_free(cons2_str); /* Sets it to NULL */
  1018. done:
  1019. if (cons2) {
  1020. smartlist_free(cons2);
  1021. }
  1022. return cons2_str;
  1023. }
  1024. /** Any consensus line longer than this means that the input is invalid. */
  1025. #define CONSENSUS_LINE_MAX_LEN (1<<20)
  1026. /**
  1027. * Helper: For every NL-terminated line in <b>s</b>, add a cdline referring to
  1028. * that line (without trailing newline) to <b>out</b>. Return -1 if there are
  1029. * any non-NL terminated lines; 0 otherwise.
  1030. *
  1031. * Unlike tor_split_lines, this function avoids ambiguity on its
  1032. * handling of a final line that isn't NL-terminated.
  1033. *
  1034. * All cdline_t objects are allocated in the provided memarea. Strings
  1035. * are not copied: if <b>s</b> changes or becomes invalid, then all
  1036. * generated cdlines will become invalid.
  1037. */
  1038. STATIC int
  1039. consensus_split_lines(smartlist_t *out, const char *s, memarea_t *area)
  1040. {
  1041. while (*s) {
  1042. const char *eol = strchr(s, '\n');
  1043. if (!eol) {
  1044. /* File doesn't end with newline. */
  1045. return -1;
  1046. }
  1047. if (eol - s > CONSENSUS_LINE_MAX_LEN) {
  1048. /* Line is far too long. */
  1049. return -1;
  1050. }
  1051. cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
  1052. line->s = s;
  1053. line->len = (uint32_t)(eol - s);
  1054. smartlist_add(out, line);
  1055. s = eol+1;
  1056. }
  1057. return 0;
  1058. }
  1059. /** Given a list of cdline_t, return a newly allocated string containing
  1060. * all of the lines, terminated with NL, concatenated.
  1061. *
  1062. * Unlike smartlist_join_strings(), avoids lossy operations on empty
  1063. * lists. */
  1064. static char *
  1065. consensus_join_lines(const smartlist_t *inp)
  1066. {
  1067. size_t n = 0;
  1068. SMARTLIST_FOREACH(inp, const cdline_t *, cdline, n += cdline->len + 1);
  1069. n += 1;
  1070. char *result = tor_malloc(n);
  1071. char *out = result;
  1072. SMARTLIST_FOREACH_BEGIN(inp, const cdline_t *, cdline) {
  1073. memcpy(out, cdline->s, cdline->len);
  1074. out += cdline->len;
  1075. *out++ = '\n';
  1076. } SMARTLIST_FOREACH_END(cdline);
  1077. *out++ = '\0';
  1078. tor_assert(out == result+n);
  1079. return result;
  1080. }
  1081. /** Given two consensus documents, try to compute a diff between them. On
  1082. * success, retun a newly allocated string containing that diff. On failure,
  1083. * return NULL. */
  1084. char *
  1085. consensus_diff_generate(const char *cons1,
  1086. const char *cons2)
  1087. {
  1088. consensus_digest_t d1, d2;
  1089. smartlist_t *lines1 = NULL, *lines2 = NULL, *result_lines = NULL;
  1090. int r1, r2;
  1091. char *result = NULL;
  1092. r1 = consensus_compute_digest(cons1, &d1);
  1093. r2 = consensus_compute_digest(cons2, &d2);
  1094. if (BUG(r1 < 0 || r2 < 0))
  1095. return NULL; // LCOV_EXCL_LINE
  1096. memarea_t *area = memarea_new();
  1097. lines1 = smartlist_new();
  1098. lines2 = smartlist_new();
  1099. if (consensus_split_lines(lines1, cons1, area) < 0)
  1100. goto done;
  1101. if (consensus_split_lines(lines2, cons2, area) < 0)
  1102. goto done;
  1103. result_lines = consdiff_gen_diff(lines1, lines2, &d1, &d2, area);
  1104. done:
  1105. if (result_lines) {
  1106. result = consensus_join_lines(result_lines);
  1107. smartlist_free(result_lines);
  1108. }
  1109. memarea_drop_all(area);
  1110. smartlist_free(lines1);
  1111. smartlist_free(lines2);
  1112. return result;
  1113. }
  1114. /** Given a consensus document and a diff, try to apply the diff to the
  1115. * consensus. On success return a newly allocated string containing the new
  1116. * consensus. On failure, return NULL. */
  1117. char *
  1118. consensus_diff_apply(const char *consensus,
  1119. const char *diff)
  1120. {
  1121. consensus_digest_t d1;
  1122. smartlist_t *lines1 = NULL, *lines2 = NULL;
  1123. int r1;
  1124. char *result = NULL;
  1125. memarea_t *area = memarea_new();
  1126. r1 = consensus_compute_digest(consensus, &d1);
  1127. if (BUG(r1 < 0))
  1128. return NULL; // LCOV_EXCL_LINE
  1129. lines1 = smartlist_new();
  1130. lines2 = smartlist_new();
  1131. if (consensus_split_lines(lines1, consensus, area) < 0)
  1132. goto done;
  1133. if (consensus_split_lines(lines2, diff, area) < 0)
  1134. goto done;
  1135. result = consdiff_apply_diff(lines1, lines2, &d1);
  1136. done:
  1137. smartlist_free(lines1);
  1138. smartlist_free(lines2);
  1139. memarea_drop_all(area);
  1140. return result;
  1141. }