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 /* The minimum length of a valid digest line in a file produced
63 by `md5sum FILE' and read by `md5sum --check'. This length does
64 not include any newline character at the end of a line. */
65 #define MIN_DIGEST_LINE_LENGTH (32 /* message digest length */ \
66 + 2 /* blank and binary indicator */ \
67 + 1 /* minimum filename length */ )
69 /* Nonzero if any of the files read were the standard input. */
70 static int have_read_stdin;
72 /* With --check, don't generate any output.
73 The exit code indicates success or failure. */
74 static int status_only = 0;
76 /* With --check, print a message to standard error warning about each
77 improperly formatted MD5 checksum line. */
80 /* The name this program was run with. */
83 static const struct option long_options[] =
85 { "binary", no_argument, 0, 'b' },
86 { "check", no_argument, 0, 'c' },
87 { "status", no_argument, 0, 2 },
88 { "string", required_argument, 0, 1 },
89 { "text", no_argument, 0, 't' },
90 { "warn", no_argument, 0, 'w' },
100 fprintf (stderr, _("Try `%s --help' for more information.\n"),
104 Usage: %s [OPTION] [FILE]...\n\
105 or: %s [OPTION] --check [FILE]\n\
106 or: %s [OPTION] --string=STRING ...\n\
107 Print or check MD5 checksums.\n\
108 With no FILE, or when FILE is -, read standard input.\n\
110 -b, --binary read files in binary mode\n\
111 -t, --text read files in text mode (default)\n\
112 -c, --check check MD5 sums against given list\n\
114 The following two options are useful only when verifying checksums:\n\
115 --status don't output anything, status code shows success\n\
116 -w, --warn warn about improperly formated MD5 checksum lines\n\
118 --string=STRING compute checksum for STRING\n\
119 --help display this help and exit\n\
120 --version output version information and exit\n\
122 The sums are computed as described in RFC 1321. When checking, the input\n\
123 should be a former output of this program. The default mode is to print\n\
124 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
125 text), and name for each FILE.\n"),
126 program_name, program_name, program_name);
128 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
132 split_3 (char *s, size_t s_len, char **u, int *binary, char **w)
135 int filename_has_newline = 0;
137 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
140 while (ISWHITE (s[i]))
143 /* The line must have at least 35 (36 if the first is a backslash)
144 more characters to contain correct message digest information.
145 Ignore this line if it is too short. */
146 if (!(s_len - i >= MIN_DIGEST_LINE_LENGTH
147 || (s[i] == '\\' && s_len - i >= 1 + MIN_DIGEST_LINE_LENGTH)))
153 filename_has_newline = 1;
157 /* The first field has to be the 32-character hexadecimal
158 representation of the message digest. If it is not followed
159 immediately by a white space it's an error. */
166 if (s[i] != ' ' && s[i] != '*')
168 *binary = (s[i++] == '*');
170 /* All characters between the type indicator and end of line are
171 significant -- that includes leading and trailing white space. */
174 if (filename_has_newline)
176 /* Translate each `\n' string in the file name to a NEWLINE,
177 and each `\\' string to a backslash. */
188 /* A valid line does not end with a backslash. */
201 /* Only `\' or `n' may follow a backslash. */
207 /* The file name may not contain a NUL. */
222 hex_digits (const char *s)
233 /* An interface to md5_stream. Operate on FILENAME (it may be "-") and
234 put the result in *MD5_RESULT. Return non-zero upon failure, zero
235 to indicate success. */
238 md5_file (const char *filename, int binary, unsigned char *md5_result)
243 if (strcmp (filename, "-") == 0)
250 /* OPENOPTS is a macro. It varies with the system.
251 Some systems distinguish between internal and
252 external text representations. */
254 fp = fopen (filename, OPENOPTS (binary));
257 error (0, errno, "%s", filename);
262 err = md5_stream (fp, md5_result);
265 error (0, errno, "%s", filename);
271 if (fp != stdin && fclose (fp) == EOF)
273 error (0, errno, "%s", filename);
281 md5_check (const char *checkfile_name, int binary)
283 FILE *checkfile_stream;
284 int n_properly_formated_lines = 0;
285 int n_mismatched_checksums = 0;
286 int n_open_or_read_failures = 0;
287 unsigned char md5buffer[16];
290 size_t line_chars_allocated;
292 if (strcmp (checkfile_name, "-") == 0)
295 checkfile_name = _("standard input");
296 checkfile_stream = stdin;
300 checkfile_stream = fopen (checkfile_name, "r");
301 if (checkfile_stream == NULL)
303 error (0, errno, "%s", checkfile_name);
310 line_chars_allocated = 0;
321 line_length = getline (&line, &line_chars_allocated, checkfile_stream);
322 if (line_length <= 0)
325 /* Ignore comment lines, which begin with a '#' character. */
329 /* Remove any trailing newline. */
330 if (line[line_length - 1] == '\n')
331 line[--line_length] = '\0';
333 err = split_3 (line, line_length, &md5num, &type_flag, &filename);
334 if (err || !hex_digits (md5num))
339 _("%s: %lu: improperly formatted MD5 checksum line"),
340 checkfile_name, (unsigned long) line_number);
345 static const char bin2hex[] = { '0', '1', '2', '3',
348 'c', 'd', 'e', 'f' };
351 ++n_properly_formated_lines;
353 fail = md5_file (filename, binary, md5buffer);
357 ++n_open_or_read_failures;
360 printf (_("%s: FAILED open or read\n"), filename);
367 /* Compare generated binary number with text representation
368 in check file. Ignore case of hex digits. */
369 for (cnt = 0; cnt < 16; ++cnt)
371 if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
372 || (TOLOWER (md5num[2 * cnt + 1])
373 != (bin2hex[md5buffer[cnt] & 0xf])))
377 ++n_mismatched_checksums;
381 printf ("%s: %s\n", filename,
382 (cnt != 16 ? _("FAILED") : _("OK")));
388 while (!feof (checkfile_stream) && !ferror (checkfile_stream));
393 if (ferror (checkfile_stream))
395 error (0, 0, _("%s: read error"), checkfile_name);
399 if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
401 error (0, errno, "%s", checkfile_name);
405 if (n_properly_formated_lines == 0)
407 /* Warn if no tests are found. */
408 error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
415 int n_computed_checkums = (n_properly_formated_lines
416 - n_open_or_read_failures);
418 if (n_open_or_read_failures > 0)
421 _("WARNING: %d of %d listed %s could not be read\n"),
422 n_open_or_read_failures, n_properly_formated_lines,
423 (n_properly_formated_lines == 1
424 ? _("file") : _("files")));
427 if (n_mismatched_checksums > 0)
430 _("WARNING: %d of %d computed %s did NOT match"),
431 n_mismatched_checksums, n_computed_checkums,
432 (n_computed_checkums == 1
433 ? _("checksum") : _("checksums")));
438 return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
439 && n_open_or_read_failures == 0) ? 0 : 1);
443 main (int argc, char **argv)
445 unsigned char md5buffer[16];
449 char **string = NULL;
450 size_t n_strings = 0;
454 /* Text is default of the Plumb/Lankester format. */
457 /* Setting values of global variables. */
458 program_name = argv[0];
459 setlocale (LC_ALL, "");
460 bindtextdomain (PACKAGE, LOCALEDIR);
461 textdomain (PACKAGE);
463 parse_long_options (argc, argv, "md5sum", PACKAGE_VERSION, usage);
465 while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL))
469 case 0: /* long option */
471 case 1: /* --string */
474 string = (char **) xmalloc ((argc - 1) * sizeof (char *));
478 string[n_strings++] = optarg;
499 usage (EXIT_FAILURE);
504 printf ("md5sum - %s\n", PACKAGE_VERSION);
508 if (n_strings > 0 && do_check)
511 _("the --string and --check options are mutually exclusive"));
512 usage (EXIT_FAILURE);
515 if (status_only && !do_check)
518 _("the --status option is meaningful only when verifying checksums"));
519 usage (EXIT_FAILURE);
522 if (warn && !do_check)
525 _("the --warn option is meaningful only when verifying checksums"));
526 usage (EXIT_FAILURE);
533 error (0, 0, _("no files may be specified when using --string"));
534 usage (EXIT_FAILURE);
536 for (i = 0; i < n_strings; ++i)
539 md5_buffer (string[i], strlen (string[i]), md5buffer);
541 for (cnt = 0; cnt < 16; ++cnt)
542 printf ("%02x", md5buffer[cnt]);
544 printf (" \"%s\"\n", string[i]);
549 if (optind + 1 < argc)
552 _("only one argument may be specified when using --check"));
553 usage (EXIT_FAILURE);
556 err = md5_check ((optind == argc) ? "-" : argv[optind], binary);
563 for (; optind < argc; ++optind)
566 char *file = argv[optind];
568 fail = md5_file (file, binary, md5buffer);
574 /* Output a leading backslash if the file name contains
576 if (strchr (file, '\n'))
579 for (i = 0; i < 16; ++i)
580 printf ("%02x", md5buffer[i]);
588 /* Translate each NEWLINE byte to the string, "\\n",
589 and each backslash to "\\\\". */
590 for (i = 0; i < strlen (file); ++i)
595 fputs ("\\n", stdout);
599 fputs ("\\\\", stdout);
612 if (fclose (stdout) == EOF)
613 error (EXIT_FAILURE, errno, _("write error"));
615 if (have_read_stdin && fclose (stdin) == EOF)
616 error (EXIT_FAILURE, errno, _("standard input"));
618 exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);