consdiff.c 41 KB

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