1 /* Compute MD5 checksum of files or strings according to the definition
2 of MD5 in RFC 1321 from April 1992.
3 Copyright (C) 95, 1996 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>. */
27 #include <sys/types.h>
29 #include "long-options.h"
35 /* Most systems do not distinguish between external and internal
36 text representations. */
37 #if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
38 # define OPENOPTS(BINARY) "r"
41 # define TEXT1TO1 "rb"
45 # define TEXT1TO1 "rb", "ctx=stm"
46 # define TEXTCNVT "r", "ctx=stm"
48 /* The following line is intended to evoke an error.
49 Using #error is not portable enough. */
50 "Cannot determine system type."
53 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
56 #if _LIBC || STDC_HEADERS
57 # define TOLOWER(c) tolower (c)
59 # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
62 /* Nonzero if any of the files read were the standard input. */
63 static int have_read_stdin;
65 /* With --check, don't generate any output.
66 The exit code indicates success or failure. */
67 static int status_only = 0;
69 /* With --check, print a message to standard error warning about each
70 improperly formatted MD5 checksum line. */
73 /* The name this program was run with. */
76 static const struct option long_options[] =
78 { "binary", no_argument, 0, 'b' },
79 { "check", no_argument, 0, 'c' },
80 { "status", no_argument, 0, 2 },
81 { "string", required_argument, 0, 1 },
82 { "text", no_argument, 0, 't' },
83 { "warn", no_argument, 0, 'w' },
93 fprintf (stderr, _("Try `%s --help' for more information.\n"),
97 Usage: %s [OPTION] [FILE]...\n\
98 or: %s [OPTION] --check [FILE]\n\
99 or: %s [OPTION] --string=STRING ...\n\
100 Print or check MD5 checksums.\n\
101 With no FILE, or when FILE is -, read standard input.\n\
103 -b, --binary read files in binary mode\n\
104 -t, --text read files in text mode (default)\n\
105 -c, --check check MD5 sums against given list\n\
107 The following two options are useful only when verifying checksums:\n\
108 --status don't output anything, status code shows success\n\
109 -w, --warn warn about improperly formated MD5 checksum lines\n\
111 --string=STRING compute checksum for STRING\n\
112 --help display this help and exit\n\
113 --version output version information and exit\n\
115 The sums are computed as described in RFC 1321. When checking, the input\n\
116 should be a former output of this program. The default mode is to print\n\
117 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
118 text), and name for each FILE.\n"),
119 program_name, program_name, program_name);
121 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
125 split_3 (char *s, size_t s_len, char **u, int *binary, char **w)
129 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
132 while (ISWHITE (s[i]))
135 /* The line has to be at least 35 characters long to contain correct
136 message digest information. */
137 if (s_len >= 32 + 2 + 1)
141 /* The first field has to be the 32-character hexadecimal
142 representation of the message digest. If it is not followed
143 immediately by a white space it's an error. */
150 if (s[i] != ' ' && s[i] != '*')
152 *binary = (s[i++] == '*');
154 /* All characters between the type indicator and end of line are
155 significant -- that includes leading and trailing white space. */
158 /* Translate each NUL byte in the file name to a NEWLINE.
160 for (/* empty */ ; i < s_len; ++i)
171 hex_digits (const char *s)
182 /* FIXME: allow newline in filename by encoding it. */
185 md5_file (const char *filename, int binary, unsigned char *md5_result)
190 if (strcmp (filename, "-") == 0)
197 /* OPENOPTS is a macro. It varies with the system.
198 Some systems distinguish between internal and
199 external text representations. */
201 fp = fopen (filename, OPENOPTS (binary));
204 error (0, errno, "%s", filename);
209 err = md5_stream (fp, md5_result);
212 error (0, errno, "%s", filename);
218 if (fp != stdin && fclose (fp) == EOF)
220 error (0, errno, "%s", filename);
228 md5_check (const char *checkfile_name, int binary)
230 FILE *checkfile_stream;
231 int n_properly_formated_lines = 0;
232 int n_mismatched_checksums = 0;
233 int n_open_or_read_failures = 0;
234 unsigned char md5buffer[16];
237 size_t line_chars_allocated;
239 if (strcmp (checkfile_name, "-") == 0)
242 checkfile_name = _("standard input");
243 checkfile_stream = stdin;
247 checkfile_stream = fopen (checkfile_name, "r");
248 if (checkfile_stream == NULL)
250 error (0, errno, "%s", checkfile_name);
257 line_chars_allocated = 0;
268 line_length = getline (&line, &line_chars_allocated, checkfile_stream);
269 if (line_length <= 0)
272 /* Ignore comment lines, which begin with a '#' character. */
276 /* Remove any trailing newline. */
277 if (line[line_length - 1] == '\n')
278 line[--line_length] = '\0';
280 /* FIXME: filename might contain NUL bytes. Map then to NEWLINEs
282 err = split_3 (line, line_length, &md5num, &type_flag, &filename);
283 if (err || !hex_digits (md5num))
288 _("%s: %lu: improperly formatted MD5 checksum line"),
289 checkfile_name, (unsigned long) line_number);
294 static const char bin2hex[] = { '0', '1', '2', '3',
297 'c', 'd', 'e', 'f' };
300 ++n_properly_formated_lines;
302 fail = md5_file (filename, binary, md5buffer);
306 ++n_open_or_read_failures;
309 printf (_("%s: FAILED open or read\n"), filename);
316 /* Compare generated binary number with text representation
317 in check file. Ignore case of hex digits. */
318 for (cnt = 0; cnt < 16; ++cnt)
320 if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
321 || (TOLOWER (md5num[2 * cnt + 1])
322 != (bin2hex[md5buffer[cnt] & 0xf])))
326 ++n_mismatched_checksums;
330 printf ("%s: %s\n", filename,
331 (cnt != 16 ? _("FAILED") : _("OK")));
337 while (!feof (checkfile_stream) && !ferror (checkfile_stream));
342 if (ferror (checkfile_stream))
344 error (0, 0, _("%s: read error"), checkfile_name);
348 if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
350 error (0, errno, "%s", checkfile_name);
354 if (n_properly_formated_lines == 0)
356 /* Warn if no tests are found. */
357 error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
364 int n_computed_checkums = (n_properly_formated_lines
365 - n_open_or_read_failures);
367 if (n_open_or_read_failures > 0)
370 _("WARNING: %d of %d listed %s could not be read\n"),
371 n_open_or_read_failures, n_properly_formated_lines,
372 (n_properly_formated_lines == 1
373 ? _("file") : _("files")));
376 if (n_mismatched_checksums > 0)
379 _("WARNING: %d of %d computed checksum%s did NOT match"),
380 n_mismatched_checksums, n_computed_checkums,
381 (n_computed_checkums == 1 ? "" : "s"));
386 return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
387 && n_open_or_read_failures == 0) ? 0 : 1);
391 main (int argc, char **argv)
393 unsigned char md5buffer[16];
397 char **string = NULL;
398 size_t n_strings = 0;
402 /* Text is default of the Plumb/Lankester format. */
405 /* Setting values of global variables. */
406 program_name = argv[0];
407 setlocale (LC_ALL, "");
408 bindtextdomain (PACKAGE, LOCALEDIR);
409 textdomain (PACKAGE);
411 parse_long_options (argc, argv, "md5sum", PACKAGE_VERSION, usage);
413 while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL))
417 case 0: /* long option */
419 case 1: /* --string */
422 string = (char **) xmalloc ((argc - 1) * sizeof (char *));
426 string[n_strings++] = optarg;
447 usage (EXIT_FAILURE);
452 printf ("md5sum - %s\n", PACKAGE_VERSION);
456 if (n_strings > 0 && do_check)
459 _("the --string and --check options are mutually exclusive"));
460 usage (EXIT_FAILURE);
463 if (status_only && !do_check)
466 _("the --status option is meaningful only when verifying checksums"));
467 usage (EXIT_FAILURE);
470 if (warn && !do_check)
473 _("the --warn option is meaningful only when verifying checksums"));
474 usage (EXIT_FAILURE);
481 error (0, 0, _("no files may be specified when using --string"));
482 usage (EXIT_FAILURE);
484 for (i = 0; i < n_strings; ++i)
487 md5_buffer (string[i], strlen (string[i]), md5buffer);
489 for (cnt = 0; cnt < 16; ++cnt)
490 printf ("%02x", md5buffer[cnt]);
492 printf (" \"%s\"\n", string[i]);
497 if (optind + 1 < argc)
500 _("only one argument may be specified when using --check"));
501 usage (EXIT_FAILURE);
504 err = md5_check ((optind == argc) ? "-" : argv[optind], binary);
511 for (; optind < argc; ++optind)
515 char *file = argv[optind];
517 fail = md5_file (file, binary, md5buffer);
523 if (strchr (file, '\n'))
526 warning: filename contains a NEWLINE character `%s'; \
527 you will not be able to verify this checksum using `md5sum --check'"),
530 for (i = 0; i < 16; ++i)
531 printf ("%02x", md5buffer[i]);
539 /* Translate NEWLINE bytes to NUL bytes.
540 But first record the length of the filename, FILE. */
541 filename_len = strlen (file);
542 for (i = 0; i < strlen (file); ++i)
547 /* Use fwrite, not printf, to output FILE --
548 now it may contain NUL bytes. */
549 fwrite (file, sizeof (char), filename_len, stdout);
555 if (fclose (stdout) == EOF)
556 error (EXIT_FAILURE, errno, _("write error"));
558 if (have_read_stdin && fclose (stdin) == EOF)
559 error (EXIT_FAILURE, errno, _("standard input"));
561 exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);