xref: /netbsd/usr.bin/cksum/cksum.c (revision f194a7c0)
1 /*	$NetBSD: cksum.c,v 1.52 2022/06/25 02:22:42 gutteridge Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * James W. Williams of NASA Goddard Space Flight Center.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*-
36  * Copyright (c) 1997 Jason R. Thorpe.  All rights reserved.
37  *
38  * This code is derived from software contributed to Berkeley by
39  * James W. Williams of NASA Goddard Space Flight Center.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. All advertising materials mentioning features or use of this software
50  *    must display the following acknowledgement:
51  *	This product includes software developed by the University of
52  *	California, Berkeley and its contributors.
53  * 4. Neither the name of the University nor the names of its contributors
54  *    may be used to endorse or promote products derived from this software
55  *    without specific prior written permission.
56  *
57  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67  * SUCH DAMAGE.
68  */
69 
70 #if HAVE_NBTOOL_CONFIG_H
71 #include "nbtool_config.h"
72 #endif
73 
74 #include <sys/cdefs.h>
75 #if defined(__COPYRIGHT) && !defined(lint)
76 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\
77  The Regents of the University of California.  All rights reserved.");
78 #endif /* not lint */
79 
80 #if defined(__RCSID) && !defined(lint)
81 #if 0
82 static char sccsid[] = "@(#)cksum.c	8.2 (Berkeley) 4/28/95";
83 #endif
84 __RCSID("$NetBSD: cksum.c,v 1.52 2022/06/25 02:22:42 gutteridge Exp $");
85 #endif /* not lint */
86 
87 #include <sys/types.h>
88 
89 #include <ctype.h>
90 #include <err.h>
91 #include <errno.h>
92 #include <fcntl.h>
93 #include <locale.h>
94 #include <md2.h>
95 #include <md4.h>
96 #include <md5.h>
97 #include <rmd160.h>
98 #include <sha1.h>
99 #include <sha2.h>
100 #include <stdio.h>
101 #include <stdlib.h>
102 #include <string.h>
103 #include <unistd.h>
104 
105 #include "extern.h"
106 
107 #define PRINT_NORMAL     0x01
108 #define PRINT_QUIET      0x02
109 
110 typedef char *(*_filefunc)(const char *, char *);
111 
112 const struct hash {
113 	const char *progname;
114 	const char *hashname;
115 	void (*stringfunc)(const char *);
116 	void (*timetrialfunc)(void);
117 	void (*testsuitefunc)(void);
118 	void (*filterfunc)(int);
119 	char *(*filefunc)(const char *, char *);
120 } hashes[] = {
121 	{ "md2", "MD2",
122 	  MD2String, MD2TimeTrial, MD2TestSuite,
123 	  MD2Filter, MD2File },
124 	{ "md4", "MD4",
125 	  MD4String, MD4TimeTrial, MD4TestSuite,
126 	  MD4Filter, MD4File },
127 	{ "md5", "MD5",
128 	  MD5String, MD5TimeTrial, MD5TestSuite,
129 	  MD5Filter, MD5File },
130 	{ "rmd160", "RMD160",
131 	  RMD160String, RMD160TimeTrial, RMD160TestSuite,
132 	  RMD160Filter, (_filefunc) RMD160File },
133 	{ "sha1", "SHA1",
134 	  SHA1String, SHA1TimeTrial, SHA1TestSuite,
135 	  SHA1Filter, (_filefunc) SHA1File },
136 	{ "sha256", "SHA256",
137 	  SHA256_String, SHA256_TimeTrial, SHA256_TestSuite,
138 	  SHA256_Filter, (_filefunc) SHA256_File },
139 	{ "sha384", "SHA384",
140 	  SHA384_String, SHA384_TimeTrial, SHA384_TestSuite,
141 	  SHA384_Filter, (_filefunc) SHA384_File },
142 	{ "sha512", "SHA512",
143 	  SHA512_String, SHA512_TimeTrial, SHA512_TestSuite,
144 	  SHA512_Filter, (_filefunc) SHA512_File },
145 	{ .progname = NULL, },
146 };
147 
148 static int	hash_digest_file(char *, const struct hash *, int);
149 __dead static void	requirehash(const char *);
150 __dead static void	usage(void);
151 
152 int
main(int argc,char ** argv)153 main(int argc, char **argv)
154 {
155 	int ch, fd, rval, pflag, nohashstdin;
156 	uint32_t val;
157 	off_t len;
158 	char *fn;
159 	const char *progname;
160 	int (*cfncn) (int, uint32_t *, off_t *);
161 	void (*pfncn) (char *, uint32_t, off_t);
162 	const struct hash *hash;
163 	int i, check_warn, do_check;
164 	int print_flags;
165 
166 	cfncn = NULL;
167 	pfncn = NULL;
168 	pflag = nohashstdin = 0;
169 	check_warn = 0;
170 	do_check = 0;
171 	print_flags = 0;
172 
173 	setlocale(LC_ALL, "");
174 
175 	progname = getprogname();
176 
177 	for (hash = hashes; hash->hashname != NULL; hash++)
178 		if (strcmp(progname, hash->progname) == 0)
179 			break;
180 
181 	if (hash->hashname == NULL) {
182 		hash = NULL;
183 
184 		if (!strcmp(progname, "sum")) {
185 			cfncn = csum1;
186 			pfncn = psum1;
187 		} else {
188 			cfncn = crc;
189 			pfncn = pcrc;
190 		}
191 	}
192 
193 	while ((ch = getopt(argc, argv, "a:cno:pqs:twx")) != -1)
194 		switch(ch) {
195 		case 'a':
196 			if (hash) {
197 				warnx("illegal use of -a option");
198 				usage();
199 			}
200 			i = 0;
201 			while (hashes[i].hashname != NULL) {
202 				if (!strcasecmp(hashes[i].hashname, optarg)) {
203 					hash = &hashes[i];
204 					break;
205 				}
206 				i++;
207 			}
208 			if (hash == NULL) {
209 				if (!strcasecmp(optarg, "old1")) {
210 					cfncn = csum1;
211 					pfncn = psum1;
212 				} else if (!strcasecmp(optarg, "old2")) {
213 					cfncn = csum2;
214 					pfncn = psum2;
215 				} else if (!strcasecmp(optarg, "crc")) {
216 					cfncn = crc;
217 					pfncn = pcrc;
218 				} else {
219 					warnx("illegal argument to -a option");
220 					usage();
221 				}
222 			}
223 			break;
224 		case 'c':
225 			do_check = 1;
226 			break;
227 		case 'n':
228 			print_flags |= PRINT_NORMAL;
229 			break;
230 		case 'o':
231 			if (hash) {
232 				warnx("%s mutually exclusive with sum",
233 				      hash->hashname);
234 				usage();
235 			}
236 			if (!strcmp(optarg, "1")) {
237 				cfncn = csum1;
238 				pfncn = psum1;
239 			} else if (!strcmp(optarg, "2")) {
240 				cfncn = csum2;
241 				pfncn = psum2;
242 			} else {
243 				warnx("illegal argument to -o option");
244 				usage();
245 			}
246 			break;
247 		case 'p':
248 			if (hash == NULL)
249 				requirehash("-p");
250 			pflag = 1;
251 			break;
252 		case 'q':
253 			print_flags |= PRINT_QUIET;
254 			break;
255 		case 's':
256 			if (hash == NULL)
257 				requirehash("-s");
258 			nohashstdin = 1;
259 			hash->stringfunc(optarg);
260 			break;
261 		case 't':
262 			if (hash == NULL)
263 				requirehash("-t");
264 			nohashstdin = 1;
265 			hash->timetrialfunc();
266 			break;
267 		case 'w':
268 			check_warn = 1;
269 			break;
270 		case 'x':
271 			if (hash == NULL)
272 				requirehash("-x");
273 			nohashstdin = 1;
274 			hash->testsuitefunc();
275 			break;
276 		case '?':
277 		default:
278 			usage();
279 		}
280 	argc -= optind;
281 	argv += optind;
282 
283 	if (do_check) {
284 		/*
285 		 * Verify checksums
286 		 */
287 		FILE *f;
288 		char buf[BUFSIZ];
289 		char *s, *p_filename, *p_cksum;
290 		int l_filename, l_cksum;
291 		char filename[BUFSIZ];
292 		char cksum[BUFSIZ];
293 		int ok,cnt,badcnt;
294 
295 		rval = 0;
296 		cnt = badcnt = 0;
297 
298 		if (argc == 0) {
299 			f = fdopen(STDIN_FILENO, "r");
300 		} else {
301 			f = fopen(argv[0], "r");
302 		}
303 		if (f == NULL)
304 			err(1, "Cannot read %s",
305 			    argc>0?argv[0]:"stdin");
306 
307 		while(fgets(buf, sizeof(buf), f) != NULL) {
308 			s = strrchr(buf, '\n');
309 			if (s)
310 				*s = '\0';
311 
312 			p_cksum = p_filename = NULL;
313 
314 			p_filename = strchr(buf, '(');
315 			if (p_filename) {
316 				/*
317 				 * Assume 'normal' output if there's a '('
318 				 */
319 				p_filename += 1;
320 				print_flags &= ~(PRINT_NORMAL);
321 
322 				p_cksum = strrchr(p_filename, ')');
323 				if (p_cksum == NULL) {
324 					if (check_warn)
325 						warnx("bogus format: %s. "
326 						      "Skipping...",
327 						      buf);
328 					rval = 1;
329 					continue;
330 				}
331  				p_cksum += 4;
332 
333 				l_cksum = strlen(p_cksum);
334 				l_filename = p_cksum - p_filename - 4;
335 
336 				/* Sanity check, and find proper hash if
337 				 * it's not the same as the current program
338 				 */
339 				if (hash == NULL ||
340 				    strncmp(buf, hash->hashname,
341 					    strlen(hash->hashname)) != 0) {
342 					/*
343 					 * Search proper hash
344 					 */
345 					const struct hash *nhash;
346 
347 					for (nhash = hashes ;
348 					     nhash->hashname != NULL;
349 					     nhash++)
350 						if (strncmp(buf,
351 							    nhash->hashname,
352 							    strlen(nhash->hashname)) == 0)
353 							break;
354 
355 
356 					if (nhash->hashname == NULL) {
357 						if (check_warn)
358 							warnx("unknown hash: %s",
359 							      buf);
360 						rval = 1;
361 						continue;
362 					} else {
363 						hash = nhash;
364 					}
365 				}
366 
367 			} else {
368 				if (hash) {
369 					int nspaces;
370 
371 					/*
372 					 * 'normal' output, no (ck)sum
373 					 */
374 					print_flags |= PRINT_NORMAL;
375 					nspaces = 1;
376 
377 					p_cksum = buf;
378 					p_filename = strchr(buf, ' ');
379 					if (p_filename == NULL) {
380 						if (check_warn)
381 							warnx("no filename in %s? "
382 							      "Skipping...", buf);
383 						rval = 1;
384 						continue;
385 					}
386 					while (isspace((unsigned char)*++p_filename))
387 						nspaces++;
388 					l_filename = strlen(p_filename);
389 					l_cksum = p_filename - buf - nspaces;
390 				} else {
391 					/*
392 					 * sum/cksum output format
393 					 */
394 					p_cksum = buf;
395 					s=strchr(p_cksum, ' ');
396 					if (s == NULL) {
397 						if (check_warn)
398 							warnx("bogus format: %s."
399 							      " Skipping...",
400 							      buf);
401 						rval = 1;
402 						continue;
403 					}
404 					l_cksum = s - p_cksum;
405 
406 					p_filename = strrchr(buf, ' ');
407 					if (p_filename == NULL) {
408 						if (check_warn)
409 							warnx("no filename in %s?"
410 							      " Skipping...",
411 							      buf);
412 						rval = 1;
413 						continue;
414 					}
415 					p_filename++;
416 					l_filename = strlen(p_filename);
417 				}
418 			}
419 
420 			strlcpy(filename, p_filename, l_filename+1);
421 			strlcpy(cksum, p_cksum, l_cksum+1);
422 
423 			if (hash) {
424 				char *h;
425 
426 				if (access(filename, R_OK) == 0
427 				    && (h = hash->filefunc(filename, NULL)) != NULL
428 				    && strcmp(cksum, h) == 0)
429 					ok = 1;
430 				else
431 					ok = 0;
432 			} else {
433 				if ((fd = open(filename, O_RDONLY, 0)) < 0) {
434 					if (check_warn)
435 						warn("%s", filename);
436 					rval = 1;
437 					ok = 0;
438 				} else {
439 					if (cfncn(fd, &val, &len))
440 						ok = 0;
441 					else {
442 						uint32_t should_val;
443 
444 						should_val =
445 						  strtoul(cksum, NULL, 10);
446 						if (val == should_val)
447 							ok = 1;
448 						else
449 							ok = 0;
450 					}
451 					close(fd);
452 				}
453 			}
454 
455 			if (! ok) {
456 				if (hash)
457 					printf("(%s) ", hash->hashname);
458 				printf("%s: FAILED\n", filename);
459 				badcnt++;
460 			}
461 			cnt++;
462 
463 		}
464 		fclose(f);
465 
466 		if (badcnt > 0)
467 			rval = 1;
468 
469 	} else {
470 		/*
471 		 * Calculate checksums
472 		 */
473 
474 		fd = STDIN_FILENO;
475 		fn = NULL;
476 		rval = 0;
477 		do {
478 			if (*argv) {
479 				fn = *argv++;
480 				if (hash != NULL) {
481 					if (hash_digest_file(fn, hash, print_flags)) {
482 						warn("%s", fn);
483 						rval = 1;
484 					}
485 					continue;
486 				}
487 				if ((fd = open(fn, O_RDONLY, 0)) < 0) {
488 					warn("%s", fn);
489 					rval = 1;
490 					continue;
491 				}
492 			} else if (hash && !nohashstdin) {
493 				hash->filterfunc(pflag);
494 			}
495 
496 			if (hash == NULL) {
497 				if (cfncn(fd, &val, &len)) {
498 					warn("%s", fn ? fn : "stdin");
499 					rval = 1;
500 				} else
501 					pfncn(fn, val, len);
502 				(void)close(fd);
503 			}
504 		} while (*argv);
505 	}
506 	exit(rval);
507 }
508 
509 static int
hash_digest_file(char * fn,const struct hash * hash,int flags)510 hash_digest_file(char *fn, const struct hash *hash, int flags)
511 {
512 	char *cp;
513 
514 	cp = hash->filefunc(fn, NULL);
515 	if (cp == NULL)
516 		return 1;
517 
518 	if (flags & PRINT_QUIET)
519 		printf("%s\n", cp);
520 	else if (flags & PRINT_NORMAL)
521 		printf("%s %s\n", cp, fn);
522 	else
523 		printf("%s (%s) = %s\n", hash->hashname, fn, cp);
524 
525 	free(cp);
526 
527 	return 0;
528 }
529 
530 static void
requirehash(const char * flg)531 requirehash(const char *flg)
532 {
533 	warnx("%s flag requires `-a algorithm'", flg);
534 	usage();
535 }
536 
537 static void
usage(void)538 usage(void)
539 {
540 	const char fileargs[] = "[file ... | -c [-w] [sumfile]]";
541 	const char sumargs[] = "[-n] [-a algorithm [-ptx] [-s string]] [-o 1|2]";
542 	const char hashargs[] = "[-nptx] [-s string]";
543 
544 	(void)fprintf(stderr, "usage: cksum %s\n             %s\n",
545 	    sumargs, fileargs);
546 	(void)fprintf(stderr, "       sum %s\n           %s\n",
547 	    sumargs, fileargs);
548 	(void)fprintf(stderr, "       md2 %s %s\n", hashargs, fileargs);
549 	(void)fprintf(stderr, "       md4 %s %s\n", hashargs, fileargs);
550 	(void)fprintf(stderr, "       md5 %s %s\n", hashargs, fileargs);
551 	(void)fprintf(stderr, "       rmd160 %s %s\n", hashargs, fileargs);
552 	(void)fprintf(stderr, "       sha1 %s %s\n", hashargs, fileargs);
553 	exit(1);
554 }
555