Repository navigation
Expand file tree
/
Copy pathcch.cpp
More file actions
567 lines (468 loc) · 19 KB
/
Copy pathcch.cpp
File metadata and controls
567 lines (468 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// SPDX-FileCopyrightText: Steven Ward
// SPDX-License-Identifier: MPL-2.0
#include "bytes_hex.hpp"
#include "cch-tree.hpp"
#include "cch.hpp"
#include "check_utils.hpp"
#include "file_input.hpp"
#include "fnv.hpp"
#include "parse_int.hpp"
#include "quote_shell_always.hpp"
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <err.h>
#include <format>
#include <getopt.h>
#include <optional>
#include <print>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
inline constexpr std::string_view program_author = "Steven Ward";
inline constexpr std::string_view program_license = "MPL-2.0";
inline constexpr std::string_view program_version = "2026-08-08";
// {{{ default values for options
inline constexpr int min_digest_size_bytes = 1;
inline constexpr int max_digest_size_bytes =
compress_castella_tree::get_max_digest_size_bytes();
inline constexpr int default_digest_size_bytes = max_digest_size_bytes / 2;
static_assert(default_digest_size_bytes >= min_digest_size_bytes);
static_assert(default_digest_size_bytes <= max_digest_size_bytes);
inline constexpr int default_mix_rate = compress_castella_hash<>::DEFAULT_MIX_RATE;
// 0 disables periodic mixing, so the valid mix rates are the contiguous range
// [0, MIX_RATE_MAX].
static_assert(compress_castella_hash<>::MIX_RATE_MIN == 1);
// Different chunk sizes give different digests.
inline constexpr int default_chunk_size = compress_castella_tree::DEFAULT_CHUNK_SIZE;
// 0 means one worker thread per available hardware thread.
inline constexpr int default_num_threads = 0;
// }}}
// {{{ options
auto digest_size_bytes = default_digest_size_bytes;
auto mix_rate = default_mix_rate;
auto chunk_size = default_chunk_size;
auto num_threads = default_num_threads;
bool use_mmap = true;
bool tag_output = true;
bool check_mode = false;
bool quiet = false;
// }}}
/// Print the version information
void
print_version()
{
std::println("{} {}", program_invocation_short_name, program_version);
std::println("Copyright (C) {}", program_author);
std::println("License {}", program_license);
std::println("Written by {}", program_author);
}
/// Print the help message
void
print_usage()
{
std::println("Usage: {} [OPTION]... [FILE]...", program_invocation_short_name);
std::println("");
std::println("Compute the Compress-Castella hash (CCH).");
std::println("If FILE is absent, or when FILE is '-', read standard input.");
std::println("CCH is a fast NON-CRYPTOGRAPHIC checksum. Do not use it where security");
std::println("matters.");
std::println("");
std::println("Options:");
std::println("");
std::println(" -V, --version");
std::println(" Print the version information, then exit.");
std::println(" -h, --help");
std::println(" Print this message, then exit.");
std::println(" -c, --check");
std::println(" Read digest lines from each FILE (or standard input) and");
std::println(" verify them. Both tagged and untagged formats are");
std::println(" accepted. A tagged line carries the digest-relevant");
std::println(" options itself. An untagged line needs the same");
std::println(" --chunk-size and --mix-rate that produced it. The");
std::println(" output size is inferred from the digest length. Empty");
std::println(" lines and lines starting with '#' are ignored.");
std::println(" (A FILE whose name contains a newline cannot be");
std::println(" verified.)");
std::println(" --chunk-size=BYTES");
std::println(" Specify the size of a tree chunk. Different chunk sizes");
std::println(" produce different digests.");
std::println(" (default={}) (minimum={}) (maximum={})",
default_chunk_size, compress_castella_tree::CHUNK_SIZE_MIN,
compress_castella_tree::CHUNK_SIZE_MAX);
std::println(" --mix-rate=RATE");
std::println(" Specify the number of absorptions (full-block inputs)");
std::println(" per state mix, or 0 to disable periodic mixing.");
std::println(" (default={}) (minimum=0) (maximum={})",
default_mix_rate, compress_castella_hash<>::MIX_RATE_MAX);
std::println(" --no-mmap");
std::println(" Do not use memory mapping to read FILE.");
std::println(" --num-threads=NUM");
std::println(" Specify the maximum number of worker threads that hash");
std::println(" chunks. 0 means one thread per available hardware");
std::println(" thread. The digest does not depend on the number of");
std::println(" threads. Only memory-mapped input uses them.");
std::println(" (default={}) (minimum=0) (maximum={})",
default_num_threads, compress_castella_tree::NUM_THREADS_MAX);
std::println(" --quiet");
std::println(" Do not print OK for each successfully verified file.");
std::println(" (only meaningful with --check)");
std::println(" --size=SIZE");
std::println(" Specify the output size (in bytes). Typical values are");
std::println(" 32, 48, and 64.");
std::println(" (default={}) (minimum={}) (maximum={})",
default_digest_size_bytes, min_digest_size_bytes, max_digest_size_bytes);
std::println(" --tag");
std::println(" Print each digest in a self-describing format that");
std::println(" embeds the digest-relevant options, so --check can");
std::println(" verify it without them. See the formats below.");
std::println(" (default)");
std::println(" (ignored with --check)");
std::println(" --untagged");
std::println(" Print each digest in the reversed style, without the");
std::println(" digest type. See the formats below.");
std::println(" (ignored with --check)");
std::println("");
std::println("Examples:");
std::println("");
std::println(" $ cch -- FILE1 FILE2");
std::println(" $ cch -- FILE1 FILE2 > SUMS");
std::println(" $ cch --check -- SUMS");
std::println(" $ cat FILE | cch --untagged");
std::println("");
std::println("The tagged and untagged formats, respectively, are:");
std::println("");
std::println(" > cch (chunk-size=C,mix-rate=R) 'FILE' = digest");
std::println(" > digest 'FILE'");
std::println("");
std::println("*See Also*");
std::println("");
std::println("castella(1), sha256sum(1), cksum(1)");
std::println("");
std::println("<https://github.com/planet36/Castella>");
std::println("");
std::println("Report bugs to <https://github.com/planet36/Castella/issues>.");
}
/// Process the command line options
/**
* \param argc the arg count
* \param argv the arg vector
*/
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
void process_options(int argc, char* argv[])
try
{
using namespace std::literals;
const char* short_options = "+Vhc";
constexpr int OPTION_HASH_VERSION = static_cast<int>(fnv1a_32("version" ));
constexpr int OPTION_HASH_HELP = static_cast<int>(fnv1a_32("help" ));
constexpr int OPTION_HASH_CHECK = static_cast<int>(fnv1a_32("check" ));
constexpr int OPTION_HASH_CHUNK_SIZE = static_cast<int>(fnv1a_32("chunk-size" ));
constexpr int OPTION_HASH_MIX_RATE = static_cast<int>(fnv1a_32("mix-rate" ));
constexpr int OPTION_HASH_NO_MMAP = static_cast<int>(fnv1a_32("no-mmap" ));
constexpr int OPTION_HASH_NUM_THREADS = static_cast<int>(fnv1a_32("num-threads"));
constexpr int OPTION_HASH_QUIET = static_cast<int>(fnv1a_32("quiet" ));
constexpr int OPTION_HASH_SIZE = static_cast<int>(fnv1a_32("size" ));
constexpr int OPTION_HASH_TAG = static_cast<int>(fnv1a_32("tag" ));
constexpr int OPTION_HASH_UNTAGGED = static_cast<int>(fnv1a_32("untagged" ));
using long_option = option;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
constexpr long_option long_options[] = {
// const char* , int , int* , int
{.name="version" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_VERSION },
{.name="help" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_HELP },
{.name="check" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_CHECK },
{.name="chunk-size" , .has_arg=required_argument, .flag=nullptr, .val=OPTION_HASH_CHUNK_SIZE },
{.name="mix-rate" , .has_arg=required_argument, .flag=nullptr, .val=OPTION_HASH_MIX_RATE },
{.name="no-mmap" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_NO_MMAP },
{.name="num-threads", .has_arg=required_argument, .flag=nullptr, .val=OPTION_HASH_NUM_THREADS},
{.name="quiet" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_QUIET },
{.name="size" , .has_arg=required_argument, .flag=nullptr, .val=OPTION_HASH_SIZE },
{.name="tag" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_TAG },
{.name="untagged" , .has_arg=no_argument , .flag=nullptr, .val=OPTION_HASH_UNTAGGED },
{.name=nullptr , .has_arg=0 , .flag=nullptr, .val=0 },
};
int c = 0;
while ((c = getopt_long(argc, argv, short_options, &long_options[0], nullptr)) != -1)
{
switch (c)
{
case 'V':
case OPTION_HASH_VERSION:
print_version();
std::exit(EXIT_SUCCESS);
break;
case 'h':
case OPTION_HASH_HELP:
print_usage();
std::exit(EXIT_SUCCESS);
break;
case 'c':
case OPTION_HASH_CHECK:
check_mode = true;
break;
case OPTION_HASH_QUIET:
quiet = true;
break;
case OPTION_HASH_TAG:
tag_output = true;
break;
case OPTION_HASH_UNTAGGED:
tag_output = false;
break;
case OPTION_HASH_CHUNK_SIZE:
chunk_size = parse_option_int(optarg, compress_castella_tree::CHUNK_SIZE_MIN,
compress_castella_tree::CHUNK_SIZE_MAX,
"--chunk-size");
break;
case OPTION_HASH_MIX_RATE:
mix_rate = parse_option_int(optarg, 0, compress_castella_hash<>::MIX_RATE_MAX,
"--mix-rate");
break;
case OPTION_HASH_NO_MMAP:
use_mmap = false;
break;
case OPTION_HASH_NUM_THREADS:
num_threads = parse_option_int(optarg, 0, compress_castella_tree::NUM_THREADS_MAX,
"--num-threads");
break;
case OPTION_HASH_SIZE:
digest_size_bytes = parse_option_int(optarg, min_digest_size_bytes,
max_digest_size_bytes, "--size");
break;
default:
std::exit(EXIT_FAILURE);
}
}
if (quiet && !check_mode)
errx(EXIT_FAILURE, "the --quiet option is only meaningful with --check");
}
catch (const std::exception& ex)
{
(void)std::fflush(stdout);
errx(EXIT_FAILURE, "%s", ex.what());
}
/// Hash the contents of the file at \a path and return the digest
/**
* Both the normal mode and --check mode build the tree here, absorb the file,
* and finalize the digest. The digest-relevant parameters are explicit,
* because a --tag check line carries its own values. The rest come from the
* globals, namely \c num_threads and \c use_mmap (through \c process_file).
*
* \exception std::system_error on I/O error
* \exception std::invalid_argument if a parameter is invalid
*/
[[nodiscard]] std::vector<std::byte>
compute_file_digest(const std::string& path,
const int digest_size,
const int rate,
const int chunk_size_bytes)
{
// Streamed input hashes inline on this thread (see USE_STREAMING_POOL).
compress_castella_tree hash_obj(rate, chunk_size_bytes, num_threads);
process_file(path, hash_obj, use_mmap);
return hash_obj.final_digest_bytes(digest_size);
}
/// Format the digest-relevant options of a --tag line (see \c print_usage)
[[nodiscard]] std::string
format_tag_params(const int chunk_size_bytes, const int rate)
{
return std::format("chunk-size={},mix-rate={}", chunk_size_bytes, rate);
}
/// The fields parsed from one checkfile line
struct check_line_fields final
{
std::string path;
std::vector<std::byte> expected_digest;
int mix_rate = 0;
int chunk_size_bytes = 0;
};
/// Whether \a digest has a size this program could have produced
[[nodiscard]] bool
is_valid_digest_size(const std::vector<std::byte>& digest) noexcept
{
return (std::ssize(digest) >= min_digest_size_bytes) &&
(std::ssize(digest) <= max_digest_size_bytes);
}
/// Parse a --tag-format line (which carries its own digest-relevant options)
[[nodiscard]] bool
parse_tagged_line(std::string_view s, check_line_fields& cl_fields)
{
if (!consume_prefix(s, "cch (chunk-size="))
return false;
if (!consume_int(s, compress_castella_tree::CHUNK_SIZE_MIN,
compress_castella_tree::CHUNK_SIZE_MAX, cl_fields.chunk_size_bytes))
return false;
if (!consume_prefix(s, ",mix-rate="))
return false;
if (!consume_int(s, 0, compress_castella_hash<>::MIX_RATE_MAX, cl_fields.mix_rate))
return false;
if (!consume_prefix(s, ") "))
return false;
if (!consume_shell_quoted(s, cl_fields.path))
return false;
if (!consume_prefix(s, " = "))
return false;
try
{
cl_fields.expected_digest = decode_hex_to_bytes(s);
}
catch (const std::invalid_argument&)
{
return false;
}
return is_valid_digest_size(cl_fields.expected_digest);
}
/// Parse an untagged line (digest, two spaces, FILE)
/**
* The digest-relevant options are taken from the command line. The FILE is
* shell-quoted, which is what this program emits. A bare FILE spanning the
* rest of the line is also accepted.
*/
[[nodiscard]] bool
parse_untagged_line(std::string_view s, check_line_fields& cl_fields)
{
const auto space_pos = s.find(' ');
if (space_pos == std::string_view::npos)
return false;
try
{
cl_fields.expected_digest = decode_hex_to_bytes(s.substr(0, space_pos));
}
catch (const std::invalid_argument&)
{
return false;
}
if (!is_valid_digest_size(cl_fields.expected_digest))
return false;
s.remove_prefix(space_pos);
if (!consume_prefix(s, " "))
return false;
if (s.starts_with('\''))
{
if (!consume_shell_quoted(s, cl_fields.path) || !std::empty(s))
return false;
}
else
{
if (std::empty(s))
return false;
cl_fields.path = s;
}
cl_fields.mix_rate = mix_rate;
cl_fields.chunk_size_bytes = chunk_size;
return true;
}
/// Parse one checkfile line, in either format
/**
* \param line the line to parse
* \return the fields, or \c std::nullopt if the line is malformed
*/
[[nodiscard]] std::optional<check_line_fields>
parse_check_line(const std::string_view line)
{
check_line_fields cl_fields;
if (parse_tagged_line(line, cl_fields))
return cl_fields;
cl_fields = {}; // a failed tag parse may have partially filled it
if (parse_untagged_line(line, cl_fields))
return cl_fields;
return std::nullopt;
}
/// Recompute the digest of an already-parsed line and update \a totals
/**
* A mismatch or an unreadable file always prints. A match prints unless
* --quiet was given.
*/
void
verify_check_line(const check_line_fields& cl_fields, verification_totals& totals)
{
std::vector<std::byte> digest_bytes;
try
{
digest_bytes = compute_file_digest(
cl_fields.path, static_cast<int>(std::ssize(cl_fields.expected_digest)),
cl_fields.mix_rate, cl_fields.chunk_size_bytes);
}
catch (const std::exception& ex)
{
(void)std::fflush(stdout);
warnx("%s", ex.what());
std::println("{}: FAILED open or read", quote_shell_always(cl_fields.path));
++totals.num_unreadable;
return;
}
if (equal_constant_time(digest_bytes, cl_fields.expected_digest))
{
++totals.num_matched;
if (!quiet)
std::println("{}: OK", quote_shell_always(cl_fields.path));
}
else
{
++totals.num_mismatched;
std::println("{}: FAILED", quote_shell_always(cl_fields.path));
}
}
// NOLINTNEXTLINE(bugprone-exception-escape)
int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[])
{
int exit_status = EXIT_SUCCESS;
process_options(argc, argv);
std::vector<std::string> paths;
for (int i = optind; i < argc; ++i)
{
paths.emplace_back(argv[i]);
}
if (paths.empty())
{
paths.emplace_back("-"); // stdin
}
if (check_mode)
{
// The paths are checkfiles (containing lines of digests to verify),
// not files to hash.
return run_check_files(paths, parse_check_line, verify_check_line);
}
for (const auto& path : paths)
{
try
{
const auto digest_bytes =
compute_file_digest(path, digest_size_bytes, mix_rate, chunk_size);
if (tag_output)
{
std::println("cch ({}) {} = {}", format_tag_params(chunk_size, mix_rate),
quote_shell_always(path), encode_bytes_to_hex(digest_bytes));
}
else
{
std::println("{} {}", encode_bytes_to_hex(digest_bytes),
quote_shell_always(path));
}
}
catch (const std::invalid_argument& ex)
{
(void)std::fflush(stdout);
warnx("invalid argument: %s", ex.what());
exit_status = EXIT_FAILURE;
break;
}
catch (const std::system_error& ex)
{
(void)std::fflush(stdout);
warnx("%s", ex.what());
exit_status = EXIT_FAILURE;
}
catch (const std::exception& ex)
{
(void)std::fflush(stdout);
warnx("%s", ex.what());
exit_status = EXIT_FAILURE;
}
}
return exit_status;
}