consdiff.c 42 KB

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