1 /* Compute MD5 or SHA1 checksum of files or strings
2 Copyright (C) 1995-2002 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>. */
24 #include <sys/types.h>
35 /* The official name of this program (e.g., no `g' prefix). */
36 #define PROGRAM_NAME (algorithm == ALG_MD5 ? "md5sum" : "shasum")
38 #define AUTHORS N_ ("Ulrich Drepper and Scott Miller")
40 /* Most systems do not distinguish between external and internal
41 text representations. */
42 /* FIXME: This begs for an autoconf test. */
44 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
45 # define TEXT1TO1 "rb"
49 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
50 # define TEXT1TO1 "rb", "ctx=stm"
51 # define TEXTCNVT "r", "ctx=stm"
53 # if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
54 # define OPENOPTS(BINARY) "r"
56 /* The following line is intended to evoke an error.
57 Using #error is not portable enough. */
58 "Cannot determine system type."
64 #define DIGEST_TYPE_STRING(Alg) ((Alg) == ALG_MD5 ? "MD5" : "SHA1")
65 #define DIGEST_STREAM(Alg) ((Alg) == ALG_MD5 ? md5_stream : sha_stream)
67 #define DIGEST_BITS(Alg) ((Alg) == ALG_MD5 ? 128 : 160)
68 #define DIGEST_HEX_BYTES(Alg) (DIGEST_BITS (Alg) / 4)
69 #define DIGEST_BIN_BYTES(Alg) (DIGEST_BITS (Alg) / 8)
71 #define MAX_DIGEST_BIN_BYTES MAX (DIGEST_BIN_BYTES (ALG_MD5), \
72 DIGEST_BIN_BYTES (ALG_SHA1))
74 /* The minimum length of a valid digest line. This length does
75 not include any newline character at the end of a line. */
76 #define MIN_DIGEST_LINE_LENGTH(Alg) \
77 (DIGEST_HEX_BYTES (Alg) /* length of hexadecimal message digest */ \
78 + 2 /* blank and binary indicator */ \
79 + 1 /* minimum filename length */ )
81 /* Nonzero if any of the files read were the standard input. */
82 static int have_read_stdin
;
84 /* The minimum length of a valid checksum line for the selected algorithm. */
85 static int min_digest_line_length
;
87 /* Set to the length of a digest hex string for the selected algorithm. */
88 static size_t digest_hex_bytes
;
90 /* With --check, don't generate any output.
91 The exit code indicates success or failure. */
92 static int status_only
= 0;
94 /* With --check, print a message to standard error warning about each
95 improperly formatted checksum line. */
98 /* Declared and set via one of the wrapper .c files. */
99 /* int algorithm = ALG_UNSPECIFIED; */
101 /* The name this program was run with. */
104 static const struct option long_options
[] =
106 { "binary", no_argument
, 0, 'b' },
107 { "check", no_argument
, 0, 'c' },
108 { "status", no_argument
, 0, 2 },
109 { "string", required_argument
, 0, 1 },
110 { "text", no_argument
, 0, 't' },
111 { "warn", no_argument
, 0, 'w' },
112 { GETOPT_HELP_OPTION_DECL
},
113 { GETOPT_VERSION_OPTION_DECL
},
121 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
126 Usage: %s [OPTION] [FILE]...\n\
127 or: %s [OPTION] --check [FILE]\n\
128 Print or check %s (%d-bit) checksums.\n\
129 With no FILE, or when FILE is -, read standard input.\n\
131 program_name
, program_name
,
132 DIGEST_TYPE_STRING (algorithm
),
133 DIGEST_BITS (algorithm
));
136 -b, --binary read files in binary mode (default on DOS/Windows)\n\
137 -c, --check check %s sums against given list\n\
138 -t, --text read files in text mode (default)\n\
141 DIGEST_TYPE_STRING (algorithm
));
143 The following two options are useful only when verifying checksums:\n\
144 --status don't output anything, status code shows success\n\
145 -w, --warn warn about improperly formated checksum lines\n\
148 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
149 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
152 The sums are computed as described in %s. When checking, the input\n\
153 should be a former output of this program. The default mode is to print\n\
154 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
155 text), and name for each FILE.\n"),
156 (algorithm
== ALG_MD5
? "RFC 1321" : "FIPS-180-1"));
157 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
160 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
164 split_3 (char *s
, size_t s_len
, unsigned char **u
, int *binary
, char **w
)
167 int escaped_filename
= 0;
169 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
172 while (ISWHITE (s
[i
]))
175 /* The line must have at least `min_digest_line_length - 1' (or one more, if
176 the first is a backslash) more characters to contain correct message digest
177 information. Ignore this line if it is too short. */
178 if (!(s_len
- i
>= min_digest_line_length
179 || (s
[i
] == '\\' && s_len
- i
>= 1 + min_digest_line_length
)))
185 escaped_filename
= 1;
187 *u
= (unsigned char *) &s
[i
];
189 /* The first field has to be the n-character hexadecimal
190 representation of the message digest. If it is not followed
191 immediately by a white space it's an error. */
192 i
+= digest_hex_bytes
;
198 if (s
[i
] != ' ' && s
[i
] != '*')
200 *binary
= (s
[i
++] == '*');
202 /* All characters between the type indicator and end of line are
203 significant -- that includes leading and trailing white space. */
206 if (escaped_filename
)
208 /* Translate each `\n' string in the file name to a NEWLINE,
209 and each `\\' string to a backslash. */
220 /* A valid line does not end with a backslash. */
233 /* Only `\' or `n' may follow a backslash. */
239 /* The file name may not contain a NUL. */
254 hex_digits (unsigned char const *s
)
265 /* An interface to the function, DIGEST_STREAM, (either md5_stream or sha_stream).
266 Operate on FILENAME (it may be "-") and put the result in *BIN_RESULT.
267 Return non-zero upon failure, zero to indicate success. */
270 digest_file (const char *filename
, int binary
, unsigned char *bin_result
,
271 int (*digest_stream
)(FILE *, void *))
276 if (STREQ (filename
, "-"))
281 /* If we need binary reads from a pipe or redirected stdin, we need
282 to switch it to BINARY mode here, since stdin is already open. */
284 SET_BINARY (fileno (stdin
));
289 /* OPENOPTS is a macro. It varies with the system.
290 Some systems distinguish between internal and
291 external text representations. */
293 fp
= fopen (filename
, OPENOPTS (binary
));
296 error (0, errno
, "%s", filename
);
301 err
= (*digest_stream
) (fp
, bin_result
);
304 error (0, errno
, "%s", filename
);
310 if (fp
!= stdin
&& fclose (fp
) == EOF
)
312 error (0, errno
, "%s", filename
);
320 digest_check (const char *checkfile_name
, int (*digest_stream
)(FILE *, void *))
322 FILE *checkfile_stream
;
323 int n_properly_formated_lines
= 0;
324 int n_mismatched_checksums
= 0;
325 int n_open_or_read_failures
= 0;
326 unsigned char bin_buffer
[MAX_DIGEST_BIN_BYTES
];
329 size_t line_chars_allocated
;
331 if (STREQ (checkfile_name
, "-"))
334 checkfile_name
= _("standard input");
335 checkfile_stream
= stdin
;
339 checkfile_stream
= fopen (checkfile_name
, "r");
340 if (checkfile_stream
== NULL
)
342 error (0, errno
, "%s", checkfile_name
);
347 SET_MODE (fileno (checkfile_stream
), O_TEXT
);
350 line_chars_allocated
= 0;
355 unsigned char *hex_digest
;
361 line_length
= getline (&line
, &line_chars_allocated
, checkfile_stream
);
362 if (line_length
<= 0)
365 /* Ignore comment lines, which begin with a '#' character. */
369 /* Remove any trailing newline. */
370 if (line
[line_length
- 1] == '\n')
371 line
[--line_length
] = '\0';
373 err
= split_3 (line
, line_length
, &hex_digest
, &binary
, &filename
);
374 if (err
|| !hex_digits (hex_digest
))
379 _("%s: %lu: improperly formatted %s checksum line"),
380 checkfile_name
, (unsigned long) line_number
,
381 DIGEST_TYPE_STRING (algorithm
));
386 static const char bin2hex
[] = { '0', '1', '2', '3',
389 'c', 'd', 'e', 'f' };
392 ++n_properly_formated_lines
;
394 fail
= digest_file (filename
, binary
, bin_buffer
, digest_stream
);
398 ++n_open_or_read_failures
;
401 printf (_("%s: FAILED open or read\n"), filename
);
407 size_t digest_bin_bytes
= digest_hex_bytes
/ 2;
409 /* Compare generated binary number with text representation
410 in check file. Ignore case of hex digits. */
411 for (cnt
= 0; cnt
< digest_bin_bytes
; ++cnt
)
413 if (TOLOWER (hex_digest
[2 * cnt
])
414 != bin2hex
[bin_buffer
[cnt
] >> 4]
415 || (TOLOWER (hex_digest
[2 * cnt
+ 1])
416 != (bin2hex
[bin_buffer
[cnt
] & 0xf])))
419 if (cnt
!= digest_bin_bytes
)
420 ++n_mismatched_checksums
;
424 printf ("%s: %s\n", filename
,
425 (cnt
!= digest_bin_bytes
? _("FAILED") : _("OK")));
431 while (!feof (checkfile_stream
) && !ferror (checkfile_stream
));
436 if (ferror (checkfile_stream
))
438 error (0, 0, _("%s: read error"), checkfile_name
);
442 if (checkfile_stream
!= stdin
&& fclose (checkfile_stream
) == EOF
)
444 error (0, errno
, "%s", checkfile_name
);
448 if (n_properly_formated_lines
== 0)
450 /* Warn if no tests are found. */
451 error (0, 0, _("%s: no properly formatted %s checksum lines found"),
452 checkfile_name
, DIGEST_TYPE_STRING (algorithm
));
458 int n_computed_checkums
= (n_properly_formated_lines
459 - n_open_or_read_failures
);
461 if (n_open_or_read_failures
> 0)
464 _("WARNING: %d of %d listed %s could not be read"),
465 n_open_or_read_failures
, n_properly_formated_lines
,
466 (n_properly_formated_lines
== 1
467 ? _("file") : _("files")));
470 if (n_mismatched_checksums
> 0)
473 _("WARNING: %d of %d computed %s did NOT match"),
474 n_mismatched_checksums
, n_computed_checkums
,
475 (n_computed_checkums
== 1
476 ? _("checksum") : _("checksums")));
481 return ((n_properly_formated_lines
> 0 && n_mismatched_checksums
== 0
482 && n_open_or_read_failures
== 0) ? 0 : 1);
486 main (int argc
, char **argv
)
488 unsigned char bin_buffer
[MAX_DIGEST_BIN_BYTES
];
491 char **string
= NULL
;
492 size_t n_strings
= 0;
494 int file_type_specified
= 0;
497 /* Binary is default on MSDOS, so the actual file contents
498 are used in computation. */
501 /* Text is default of the Plumb/Lankester format. */
505 /* Setting values of global variables. */
506 program_name
= argv
[0];
507 setlocale (LC_ALL
, "");
508 bindtextdomain (PACKAGE
, LOCALEDIR
);
509 textdomain (PACKAGE
);
511 atexit (close_stdout
);
513 while ((opt
= getopt_long (argc
, argv
, "bctw", long_options
, NULL
)) != -1)
516 case 0: /* long option */
518 case 1: /* --string */
521 string
= (char **) xmalloc ((argc
- 1) * sizeof (char *));
525 string
[n_strings
++] = optarg
;
529 file_type_specified
= 1;
540 file_type_specified
= 1;
547 case_GETOPT_HELP_CHAR
;
548 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
550 usage (EXIT_FAILURE
);
553 min_digest_line_length
= MIN_DIGEST_LINE_LENGTH (algorithm
);
554 digest_hex_bytes
= DIGEST_HEX_BYTES (algorithm
);
556 if (file_type_specified
&& do_check
)
558 error (0, 0, _("the --binary and --text options are meaningless when \
559 verifying checksums"));
560 usage (EXIT_FAILURE
);
563 if (n_strings
> 0 && do_check
)
566 _("the --string and --check options are mutually exclusive"));
567 usage (EXIT_FAILURE
);
570 if (status_only
&& !do_check
)
573 _("the --status option is meaningful only when verifying checksums"));
574 usage (EXIT_FAILURE
);
577 if (warn
&& !do_check
)
580 _("the --warn option is meaningful only when verifying checksums"));
581 usage (EXIT_FAILURE
);
590 error (0, 0, _("no files may be specified when using --string"));
591 usage (EXIT_FAILURE
);
593 for (i
= 0; i
< n_strings
; ++i
)
596 if (algorithm
== ALG_MD5
)
597 md5_buffer (string
[i
], strlen (string
[i
]), bin_buffer
);
599 sha_buffer (string
[i
], strlen (string
[i
]), bin_buffer
);
601 for (cnt
= 0; cnt
< (digest_hex_bytes
/ 2); ++cnt
)
602 printf ("%02x", bin_buffer
[cnt
]);
604 printf (" \"%s\"\n", string
[i
]);
609 if (optind
+ 1 < argc
)
612 _("only one argument may be specified when using --check"));
613 usage (EXIT_FAILURE
);
616 err
= digest_check ((optind
== argc
) ? "-" : argv
[optind
],
617 DIGEST_STREAM (algorithm
));
624 for (; optind
< argc
; ++optind
)
627 char *file
= argv
[optind
];
629 fail
= digest_file (file
, binary
, bin_buffer
,
630 DIGEST_STREAM (algorithm
));
636 /* Output a leading backslash if the file name contains
637 a newline or backslash. */
638 if (strchr (file
, '\n') || strchr (file
, '\\'))
641 for (i
= 0; i
< (digest_hex_bytes
/ 2); ++i
)
642 printf ("%02x", bin_buffer
[i
]);
650 /* Translate each NEWLINE byte to the string, "\\n",
651 and each backslash to "\\\\". */
652 for (i
= 0; i
< strlen (file
); ++i
)
657 fputs ("\\n", stdout
);
661 fputs ("\\\\", stdout
);
674 if (have_read_stdin
&& fclose (stdin
) == EOF
)
675 error (EXIT_FAILURE
, errno
, _("standard input"));
677 exit (err
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);