.
[coreutils.git] / src / md5sum.c
blob31cd521555027d36905c95f8df37a30c50cf7103
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)
8 any later version.
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>. */
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <getopt.h>
26 #include <stdio.h>
27 #include <sys/types.h>
29 #include "long-options.h"
30 #include "md5.h"
31 #include "getline.h"
32 #include "system.h"
33 #include "error.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"
39 #else
40 # ifdef MSDOS
41 # define TEXT1TO1 "rb"
42 # define TEXTCNVT "r"
43 # else
44 # if defined VMS
45 # define TEXT1TO1 "rb", "ctx=stm"
46 # define TEXTCNVT "r", "ctx=stm"
47 # else
48 /* The following line is intended to evoke an error.
49 Using #error is not portable enough. */
50 "Cannot determine system type."
51 # endif
52 # endif
53 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
54 #endif
56 #if _LIBC || STDC_HEADERS
57 # define TOLOWER(c) tolower (c)
58 #else
59 # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
60 #endif
62 /* The string with which to replace NEWLINE characters in filenames.
63 This is required to make it so md5sum --check can parse the output
64 of `md5sum FILENAME' for FILENAME contain NL characters. */
65 #define NEWLINE_REPLACEMENT_STRING "<\"NL'\\>"
67 #define NEWLINE_REPLACEMENT_STRING_LENGTH \
68 (sizeof (NEWLINE_REPLACEMENT_STRING) - 1)
70 /* Nonzero if any of the files read were the standard input. */
71 static int have_read_stdin;
73 /* With --check, don't generate any output.
74 The exit code indicates success or failure. */
75 static int status_only = 0;
77 /* With --check, print a message to standard error warning about each
78 improperly formatted MD5 checksum line. */
79 static int warn = 0;
81 /* The name this program was run with. */
82 char *program_name;
84 static const struct option long_options[] =
86 { "binary", no_argument, 0, 'b' },
87 { "check", no_argument, 0, 'c' },
88 { "status", no_argument, 0, 2 },
89 { "string", required_argument, 0, 1 },
90 { "text", no_argument, 0, 't' },
91 { "warn", no_argument, 0, 'w' },
92 { NULL, 0, NULL, 0 }
95 char *xmalloc ();
97 static void
98 usage (int status)
100 if (status != 0)
101 fprintf (stderr, _("Try `%s --help' for more information.\n"),
102 program_name);
103 else
104 printf (_("\
105 Usage: %s [OPTION] [FILE]...\n\
106 or: %s [OPTION] --check [FILE]\n\
107 or: %s [OPTION] --string=STRING ...\n\
108 Print or check MD5 checksums.\n\
109 With no FILE, or when FILE is -, read standard input.\n\
111 -b, --binary read files in binary mode\n\
112 -t, --text read files in text mode (default)\n\
113 -c, --check check MD5 sums against given list\n\
115 The following two options are useful only when verifying checksums:\n\
116 --status don't output anything, status code shows success\n\
117 -w, --warn warn about improperly formated MD5 checksum lines\n\
119 --string=STRING compute checksum for STRING\n\
120 --help display this help and exit\n\
121 --version output version information and exit\n\
123 The sums are computed as described in RFC 1321. When checking, the input\n\
124 should be a former output of this program. The default mode is to print\n\
125 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
126 text), and name for each FILE.\n"),
127 program_name, program_name, program_name);
129 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
132 static int
133 split_3 (char *s, size_t s_len, char **u, int *binary, char **w)
135 size_t i;
137 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
139 i = 0;
140 while (ISWHITE (s[i]))
141 ++i;
143 /* The line has to be at least 35 characters long to contain correct
144 message digest information. */
145 if (s_len >= 32 + 2 + 1)
147 char *p;
148 *u = &s[i];
150 /* The first field has to be the 32-character hexadecimal
151 representation of the message digest. If it is not followed
152 immediately by a white space it's an error. */
153 i += 32;
154 if (!ISWHITE (s[i]))
155 return 1;
157 s[i++] = '\0';
159 if (s[i] != ' ' && s[i] != '*')
160 return 1;
161 *binary = (s[i++] == '*');
163 /* All characters between the type indicator and end of line are
164 significant -- that includes leading and trailing white space. */
165 *w = &s[i];
167 /* Translate each NEWLINE_REPLACEMENT_STRING in the file name
168 to a NEWLINE. */
169 p = &s[i];
170 while ((p = strstr (p, NEWLINE_REPLACEMENT_STRING)))
172 size_t len;
174 *p++ = '\n';
175 len = s_len - (p - s) - (NEWLINE_REPLACEMENT_STRING_LENGTH - 1) + 1;
176 memmove (p, p + NEWLINE_REPLACEMENT_STRING_LENGTH - 1, len);
177 s_len -= NEWLINE_REPLACEMENT_STRING_LENGTH - 1;
179 return 0;
181 return 1;
184 static int
185 hex_digits (const char *s)
187 while (*s)
189 if (!ISXDIGIT (*s))
190 return 0;
191 ++s;
193 return 1;
196 /* FIXME: allow newline in filename by encoding it. */
198 static int
199 md5_file (const char *filename, int binary, unsigned char *md5_result)
201 FILE *fp;
202 int err;
204 if (strcmp (filename, "-") == 0)
206 have_read_stdin = 1;
207 fp = stdin;
209 else
211 /* OPENOPTS is a macro. It varies with the system.
212 Some systems distinguish between internal and
213 external text representations. */
215 fp = fopen (filename, OPENOPTS (binary));
216 if (fp == NULL)
218 error (0, errno, "%s", filename);
219 return 1;
223 err = md5_stream (fp, md5_result);
224 if (err)
226 error (0, errno, "%s", filename);
227 if (fp != stdin)
228 fclose (fp);
229 return 1;
232 if (fp != stdin && fclose (fp) == EOF)
234 error (0, errno, "%s", filename);
235 return 1;
238 return 0;
241 static int
242 md5_check (const char *checkfile_name, int binary)
244 FILE *checkfile_stream;
245 int n_properly_formated_lines = 0;
246 int n_mismatched_checksums = 0;
247 int n_open_or_read_failures = 0;
248 unsigned char md5buffer[16];
249 size_t line_number;
250 char *line;
251 size_t line_chars_allocated;
253 if (strcmp (checkfile_name, "-") == 0)
255 have_read_stdin = 1;
256 checkfile_name = _("standard input");
257 checkfile_stream = stdin;
259 else
261 checkfile_stream = fopen (checkfile_name, "r");
262 if (checkfile_stream == NULL)
264 error (0, errno, "%s", checkfile_name);
265 return 1;
269 line_number = 0;
270 line = NULL;
271 line_chars_allocated = 0;
274 char *filename;
275 int type_flag;
276 char *md5num;
277 int err;
278 int line_length;
280 ++line_number;
282 line_length = getline (&line, &line_chars_allocated, checkfile_stream);
283 if (line_length <= 0)
284 break;
286 /* Ignore comment lines, which begin with a '#' character. */
287 if (line[0] == '#')
288 continue;
290 /* Remove any trailing newline. */
291 if (line[line_length - 1] == '\n')
292 line[--line_length] = '\0';
294 err = split_3 (line, line_length, &md5num, &type_flag, &filename);
295 if (err || !hex_digits (md5num))
297 if (warn)
299 error (0, 0,
300 _("%s: %lu: improperly formatted MD5 checksum line"),
301 checkfile_name, (unsigned long) line_number);
304 else
306 static const char bin2hex[] = { '0', '1', '2', '3',
307 '4', '5', '6', '7',
308 '8', '9', 'a', 'b',
309 'c', 'd', 'e', 'f' };
310 int fail;
312 ++n_properly_formated_lines;
314 fail = md5_file (filename, binary, md5buffer);
316 if (fail)
318 ++n_open_or_read_failures;
319 if (!status_only)
321 printf (_("%s: FAILED open or read\n"), filename);
322 fflush (stdout);
325 else
327 size_t cnt;
328 /* Compare generated binary number with text representation
329 in check file. Ignore case of hex digits. */
330 for (cnt = 0; cnt < 16; ++cnt)
332 if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
333 || (TOLOWER (md5num[2 * cnt + 1])
334 != (bin2hex[md5buffer[cnt] & 0xf])))
335 break;
337 if (cnt != 16)
338 ++n_mismatched_checksums;
340 if (!status_only)
342 printf ("%s: %s\n", filename,
343 (cnt != 16 ? _("FAILED") : _("OK")));
344 fflush (stdout);
349 while (!feof (checkfile_stream) && !ferror (checkfile_stream));
351 if (line)
352 free (line);
354 if (ferror (checkfile_stream))
356 error (0, 0, _("%s: read error"), checkfile_name);
357 return 1;
360 if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
362 error (0, errno, "%s", checkfile_name);
363 return 1;
366 if (n_properly_formated_lines == 0)
368 /* Warn if no tests are found. */
369 error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
370 checkfile_name);
372 else
374 if (!status_only)
376 int n_computed_checkums = (n_properly_formated_lines
377 - n_open_or_read_failures);
379 if (n_open_or_read_failures > 0)
381 error (0, 0,
382 _("WARNING: %d of %d listed %s could not be read\n"),
383 n_open_or_read_failures, n_properly_formated_lines,
384 (n_properly_formated_lines == 1
385 ? _("file") : _("files")));
388 if (n_mismatched_checksums > 0)
390 error (0, 0,
391 _("WARNING: %d of %d computed checksum%s did NOT match"),
392 n_mismatched_checksums, n_computed_checkums,
393 (n_computed_checkums == 1 ? "" : "s"));
398 return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
399 && n_open_or_read_failures == 0) ? 0 : 1);
403 main (int argc, char **argv)
405 unsigned char md5buffer[16];
406 int do_check = 0;
407 int do_version = 0;
408 int opt;
409 char **string = NULL;
410 size_t n_strings = 0;
411 size_t i;
412 size_t err = 0;
414 /* Text is default of the Plumb/Lankester format. */
415 int binary = 0;
417 /* Setting values of global variables. */
418 program_name = argv[0];
419 setlocale (LC_ALL, "");
420 bindtextdomain (PACKAGE, LOCALEDIR);
421 textdomain (PACKAGE);
423 parse_long_options (argc, argv, "md5sum", PACKAGE_VERSION, usage);
425 while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL))
426 != EOF)
427 switch (opt)
429 case 0: /* long option */
430 break;
431 case 1: /* --string */
433 if (string == NULL)
434 string = (char **) xmalloc ((argc - 1) * sizeof (char *));
436 if (optarg == NULL)
437 optarg = "";
438 string[n_strings++] = optarg;
440 break;
441 case 'b':
442 binary = 1;
443 break;
444 case 'c':
445 do_check = 1;
446 break;
447 case 2:
448 status_only = 1;
449 warn = 0;
450 break;
451 case 't':
452 binary = 0;
453 break;
454 case 'w':
455 status_only = 0;
456 warn = 1;
457 break;
458 default:
459 usage (EXIT_FAILURE);
462 if (do_version)
464 printf ("md5sum - %s\n", PACKAGE_VERSION);
465 exit (EXIT_SUCCESS);
468 if (n_strings > 0 && do_check)
470 error (0, 0,
471 _("the --string and --check options are mutually exclusive"));
472 usage (EXIT_FAILURE);
475 if (status_only && !do_check)
477 error (0, 0,
478 _("the --status option is meaningful only when verifying checksums"));
479 usage (EXIT_FAILURE);
482 if (warn && !do_check)
484 error (0, 0,
485 _("the --warn option is meaningful only when verifying checksums"));
486 usage (EXIT_FAILURE);
489 if (n_strings > 0)
491 if (optind < argc)
493 error (0, 0, _("no files may be specified when using --string"));
494 usage (EXIT_FAILURE);
496 for (i = 0; i < n_strings; ++i)
498 size_t cnt;
499 md5_buffer (string[i], strlen (string[i]), md5buffer);
501 for (cnt = 0; cnt < 16; ++cnt)
502 printf ("%02x", md5buffer[cnt]);
504 printf (" \"%s\"\n", string[i]);
507 else if (do_check)
509 if (optind + 1 < argc)
511 error (0, 0,
512 _("only one argument may be specified when using --check"));
513 usage (EXIT_FAILURE);
516 err = md5_check ((optind == argc) ? "-" : argv[optind], binary);
518 else
520 if (optind == argc)
521 argv[argc++] = "-";
523 for (; optind < argc; ++optind)
525 size_t i;
526 int fail;
527 char *file = argv[optind];
529 fail = md5_file (file, binary, md5buffer);
530 err |= fail;
531 if (!fail)
533 size_t filename_len;
535 for (i = 0; i < 16; ++i)
536 printf ("%02x", md5buffer[i]);
538 putchar (' ');
539 if (binary)
540 putchar ('*');
541 else
542 putchar (' ');
544 /* Translate each NEWLINE byte to the string,
545 NEWLINE_REPLACEMENT_STRING. But first record
546 the length of the filename, FILE. */
547 filename_len = strlen (file);
548 for (i = 0; i < filename_len; ++i)
550 if (file[i] == '\n')
551 fputs (NEWLINE_REPLACEMENT_STRING, stdout);
552 else
553 putchar (file[i]);
555 putchar ('\n');
560 if (fclose (stdout) == EOF)
561 error (EXIT_FAILURE, errno, _("write error"));
563 if (have_read_stdin && fclose (stdin) == EOF)
564 error (EXIT_FAILURE, errno, _("standard input"));
566 exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);