Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/pkg
Path: blob/main/src/checksum.c
5235 views
1
/*-
2
* Copyright (c) 2026 Baptiste Daroussin <[email protected]>
3
*
4
* SPDX-License-Identifier: BSD-2-Clause
5
*/
6
7
#include <err.h>
8
#include <getopt.h>
9
#include <stdio.h>
10
#include <string.h>
11
#include <unistd.h>
12
13
#include <pkg.h>
14
#include <pkg/checksum.h>
15
#include "pkgcli.h"
16
17
void
18
usage_checksum(void)
19
{
20
fprintf(stderr,
21
"Usage: pkg checksum [-qt <type>] [-c <hash>] <file> ...\n\n");
22
fprintf(stderr, "Types: sha256_hex (default), sha256_base32, "
23
"blake2_base32, blake2s_base32\n\n");
24
fprintf(stderr, "For more information see 'pkg help checksum'.\n");
25
}
26
27
int
28
exec_checksum(int argc, char **argv)
29
{
30
const char *type_str = "blake2_base32";
31
const char *check = NULL;
32
int ch;
33
int retcode = EXIT_SUCCESS;
34
35
struct option longopts[] = {
36
{ "quiet", no_argument, NULL, 'q' },
37
{ "type", required_argument, NULL, 't' },
38
{ "check", required_argument, NULL, 'c' },
39
{ NULL, 0, NULL, 0 },
40
};
41
42
while ((ch = getopt_long(argc, argv, "+qt:c:", longopts, NULL)) != -1) {
43
switch (ch) {
44
case 'q':
45
quiet = true;
46
break;
47
case 't':
48
type_str = optarg;
49
break;
50
case 'c':
51
check = optarg;
52
break;
53
default:
54
usage_checksum();
55
return (EXIT_FAILURE);
56
}
57
}
58
59
argc -= optind;
60
argv += optind;
61
62
if (argc < 1) {
63
usage_checksum();
64
return (EXIT_FAILURE);
65
}
66
67
pkg_checksum_type_t type = pkg_checksum_type_from_string(type_str);
68
if (type == PKG_HASH_TYPE_UNKNOWN) {
69
warnx("unknown checksum type: %s", type_str);
70
return (EXIT_FAILURE);
71
}
72
73
while (argc >= 1) {
74
if (check != NULL) {
75
/* Validate mode */
76
int ret = pkg_checksum_validate_file(argv[0], check);
77
if (ret != 0) {
78
if (!quiet)
79
printf("%s: FAILED\n", argv[0]);
80
retcode = EXIT_FAILURE;
81
} else {
82
if (!quiet)
83
printf("%s: OK\n", argv[0]);
84
}
85
} else {
86
/* Generate mode */
87
char *sum = pkg_checksum_generate_file(argv[0], type);
88
if (sum == NULL) {
89
warnx("cannot compute checksum for %s",
90
argv[0]);
91
retcode = EXIT_FAILURE;
92
} else {
93
if (quiet)
94
printf("%s\n", sum);
95
else
96
printf("%s (%s)\n", sum, argv[0]);
97
free(sum);
98
}
99
}
100
101
argc--;
102
argv++;
103
}
104
105
return (retcode);
106
}
107
108