*** empty log message ***
[coreutils.git] / src / md5sum.c
blobdccf9097722be7c9943b03c87317d990ad216f2a
1 /* Compute MD5 checksum of files or strings according to the definition
2 of MD5 in RFC 1321 from April 1992.
3 Copyright (C) 1995-1999 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 "md5.h"
30 #include "getline.h"
31 #include "system.h"
32 #include "error.h"
34 /* The official name of this program (e.g., no `g' prefix). */
35 #define PROGRAM_NAME "md5sum"
37 #define AUTHORS "Ulrich Drepper"
39 /* Most systems do not distinguish between external and internal
40 text representations. */
41 /* FIXME: This begs for an autoconf test. */
42 #if O_BINARY
43 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
44 # define TEXT1TO1 "rb"
45 # define TEXTCNVT "r"
46 #else
47 # if defined VMS
48 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
49 # define TEXT1TO1 "rb", "ctx=stm"
50 # define TEXTCNVT "r", "ctx=stm"
51 # else
52 # if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
53 # define OPENOPTS(BINARY) "r"
54 # else
55 /* The following line is intended to evoke an error.
56 Using #error is not portable enough. */
57 "Cannot determine system type."
58 # endif
59 # endif
60 #endif
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. */
78 static int warn = 0;
80 /* The name this program was run with. */
81 char *program_name;
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' },
91 { GETOPT_HELP_OPTION_DECL },
92 { GETOPT_VERSION_OPTION_DECL },
93 { NULL, 0, NULL, 0 }
96 void
97 usage (int status)
99 if (status != 0)
100 fprintf (stderr, _("Try `%s --help' for more information.\n"),
101 program_name);
102 else
104 printf (_("\
105 Usage: %s [OPTION] [FILE]...\n\
106 or: %s [OPTION] --check [FILE]\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 (default on DOS/Windows)\n\
111 -c, --check check MD5 sums against given list\n\
112 -t, --text read files in text mode (default)\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 --help display this help and exit\n\
119 --version output version information and exit\n\
121 The sums are computed as described in RFC 1321. When checking, the input\n\
122 should be a former output of this program. The default mode is to print\n\
123 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
124 text), and name for each FILE.\n"),
125 program_name, program_name);
126 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
129 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
132 static int
133 split_3 (char *s, size_t s_len, unsigned char **u, int *binary, char **w)
135 size_t i;
136 int escaped_filename = 0;
138 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
140 i = 0;
141 while (ISWHITE (s[i]))
142 ++i;
144 /* The line must have at least 35 (36 if the first is a backslash)
145 more characters to contain correct message digest information.
146 Ignore this line if it is too short. */
147 if (!(s_len - i >= MIN_DIGEST_LINE_LENGTH
148 || (s[i] == '\\' && s_len - i >= 1 + MIN_DIGEST_LINE_LENGTH)))
149 return 1;
151 if (s[i] == '\\')
153 ++i;
154 escaped_filename = 1;
156 *u = (unsigned char *) &s[i];
158 /* The first field has to be the 32-character hexadecimal
159 representation of the message digest. If it is not followed
160 immediately by a white space it's an error. */
161 i += 32;
162 if (!ISWHITE (s[i]))
163 return 1;
165 s[i++] = '\0';
167 if (s[i] != ' ' && s[i] != '*')
168 return 1;
169 *binary = (s[i++] == '*');
171 /* All characters between the type indicator and end of line are
172 significant -- that includes leading and trailing white space. */
173 *w = &s[i];
175 if (escaped_filename)
177 /* Translate each `\n' string in the file name to a NEWLINE,
178 and each `\\' string to a backslash. */
180 char *dst = &s[i];
182 while (i < s_len)
184 switch (s[i])
186 case '\\':
187 if (i == s_len - 1)
189 /* A valid line does not end with a backslash. */
190 return 1;
192 ++i;
193 switch (s[i++])
195 case 'n':
196 *dst++ = '\n';
197 break;
198 case '\\':
199 *dst++ = '\\';
200 break;
201 default:
202 /* Only `\' or `n' may follow a backslash. */
203 return 1;
205 break;
207 case '\0':
208 /* The file name may not contain a NUL. */
209 return 1;
210 break;
212 default:
213 *dst++ = s[i++];
214 break;
217 *dst = '\0';
219 return 0;
222 static int
223 hex_digits (unsigned char const *s)
225 while (*s)
227 if (!ISXDIGIT (*s))
228 return 0;
229 ++s;
231 return 1;
234 /* An interface to md5_stream. Operate on FILENAME (it may be "-") and
235 put the result in *MD5_RESULT. Return non-zero upon failure, zero
236 to indicate success. */
238 static int
239 md5_file (const char *filename, int binary, unsigned char *md5_result)
241 FILE *fp;
242 int err;
244 if (STREQ (filename, "-"))
246 have_read_stdin = 1;
247 fp = stdin;
248 #if O_BINARY
249 /* If we need binary reads from a pipe or redirected stdin, we need
250 to switch it to BINARY mode here, since stdin is already open. */
251 if (binary)
252 SET_BINARY (fileno (stdin));
253 #endif
255 else
257 /* OPENOPTS is a macro. It varies with the system.
258 Some systems distinguish between internal and
259 external text representations. */
261 fp = fopen (filename, OPENOPTS (binary));
262 if (fp == NULL)
264 error (0, errno, "%s", filename);
265 return 1;
269 err = md5_stream (fp, md5_result);
270 if (err)
272 error (0, errno, "%s", filename);
273 if (fp != stdin)
274 fclose (fp);
275 return 1;
278 if (fp != stdin && fclose (fp) == EOF)
280 error (0, errno, "%s", filename);
281 return 1;
284 return 0;
287 static int
288 md5_check (const char *checkfile_name)
290 FILE *checkfile_stream;
291 int n_properly_formated_lines = 0;
292 int n_mismatched_checksums = 0;
293 int n_open_or_read_failures = 0;
294 unsigned char md5buffer[16];
295 size_t line_number;
296 char *line;
297 size_t line_chars_allocated;
299 if (STREQ (checkfile_name, "-"))
301 have_read_stdin = 1;
302 checkfile_name = _("standard input");
303 checkfile_stream = stdin;
305 else
307 checkfile_stream = fopen (checkfile_name, "r");
308 if (checkfile_stream == NULL)
310 error (0, errno, "%s", checkfile_name);
311 return 1;
315 line_number = 0;
316 line = NULL;
317 line_chars_allocated = 0;
320 char *filename;
321 int binary;
322 unsigned char *md5num;
323 int err;
324 int line_length;
326 ++line_number;
328 line_length = getline (&line, &line_chars_allocated, checkfile_stream);
329 if (line_length <= 0)
330 break;
332 /* Ignore comment lines, which begin with a '#' character. */
333 if (line[0] == '#')
334 continue;
336 /* Remove any trailing newline. */
337 if (line[line_length - 1] == '\n')
338 line[--line_length] = '\0';
340 err = split_3 (line, line_length, &md5num, &binary, &filename);
341 if (err || !hex_digits (md5num))
343 if (warn)
345 error (0, 0,
346 _("%s: %lu: improperly formatted MD5 checksum line"),
347 checkfile_name, (unsigned long) line_number);
350 else
352 static const char bin2hex[] = { '0', '1', '2', '3',
353 '4', '5', '6', '7',
354 '8', '9', 'a', 'b',
355 'c', 'd', 'e', 'f' };
356 int fail;
358 ++n_properly_formated_lines;
360 fail = md5_file (filename, binary, md5buffer);
362 if (fail)
364 ++n_open_or_read_failures;
365 if (!status_only)
367 printf (_("%s: FAILED open or read\n"), filename);
368 fflush (stdout);
371 else
373 size_t cnt;
374 /* Compare generated binary number with text representation
375 in check file. Ignore case of hex digits. */
376 for (cnt = 0; cnt < 16; ++cnt)
378 if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
379 || (TOLOWER (md5num[2 * cnt + 1])
380 != (bin2hex[md5buffer[cnt] & 0xf])))
381 break;
383 if (cnt != 16)
384 ++n_mismatched_checksums;
386 if (!status_only)
388 printf ("%s: %s\n", filename,
389 (cnt != 16 ? _("FAILED") : _("OK")));
390 fflush (stdout);
395 while (!feof (checkfile_stream) && !ferror (checkfile_stream));
397 if (line)
398 free (line);
400 if (ferror (checkfile_stream))
402 error (0, 0, _("%s: read error"), checkfile_name);
403 return 1;
406 if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
408 error (0, errno, "%s", checkfile_name);
409 return 1;
412 if (n_properly_formated_lines == 0)
414 /* Warn if no tests are found. */
415 error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
416 checkfile_name);
418 else
420 if (!status_only)
422 int n_computed_checkums = (n_properly_formated_lines
423 - n_open_or_read_failures);
425 if (n_open_or_read_failures > 0)
427 error (0, 0,
428 _("WARNING: %d of %d listed %s could not be read\n"),
429 n_open_or_read_failures, n_properly_formated_lines,
430 (n_properly_formated_lines == 1
431 ? _("file") : _("files")));
434 if (n_mismatched_checksums > 0)
436 error (0, 0,
437 _("WARNING: %d of %d computed %s did NOT match"),
438 n_mismatched_checksums, n_computed_checkums,
439 (n_computed_checkums == 1
440 ? _("checksum") : _("checksums")));
445 return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
446 && n_open_or_read_failures == 0) ? 0 : 1);
450 main (int argc, char **argv)
452 unsigned char md5buffer[16];
453 int do_check = 0;
454 int opt;
455 char **string = NULL;
456 size_t n_strings = 0;
457 size_t err = 0;
458 int file_type_specified = 0;
460 #if O_BINARY
461 /* Binary is default on MSDOS, so the actual file contents
462 are used in computation. */
463 int binary = 1;
464 #else
465 /* Text is default of the Plumb/Lankester format. */
466 int binary = 0;
467 #endif
469 /* Setting values of global variables. */
470 program_name = argv[0];
471 setlocale (LC_ALL, "");
472 bindtextdomain (PACKAGE, LOCALEDIR);
473 textdomain (PACKAGE);
475 while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
476 switch (opt)
478 case 0: /* long option */
479 break;
480 case 1: /* --string */
482 if (string == NULL)
483 string = (char **) xmalloc ((argc - 1) * sizeof (char *));
485 if (optarg == NULL)
486 optarg = "";
487 string[n_strings++] = optarg;
489 break;
490 case 'b':
491 file_type_specified = 1;
492 binary = 1;
493 break;
494 case 'c':
495 do_check = 1;
496 break;
497 case 2:
498 status_only = 1;
499 warn = 0;
500 break;
501 case 't':
502 file_type_specified = 1;
503 binary = 0;
504 break;
505 case 'w':
506 status_only = 0;
507 warn = 1;
508 break;
509 case_GETOPT_HELP_CHAR;
510 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
511 default:
512 usage (EXIT_FAILURE);
515 if (file_type_specified && do_check)
517 error (0, 0, _("the --binary and --text options are meaningless when \
518 verifying checksums"));
519 usage (EXIT_FAILURE);
522 if (n_strings > 0 && do_check)
524 error (0, 0,
525 _("the --string and --check options are mutually exclusive"));
526 usage (EXIT_FAILURE);
529 if (status_only && !do_check)
531 error (0, 0,
532 _("the --status option is meaningful only when verifying checksums"));
533 usage (EXIT_FAILURE);
536 if (warn && !do_check)
538 error (0, 0,
539 _("the --warn option is meaningful only when verifying checksums"));
540 usage (EXIT_FAILURE);
543 if (n_strings > 0)
545 size_t i;
547 if (optind < argc)
549 error (0, 0, _("no files may be specified when using --string"));
550 usage (EXIT_FAILURE);
552 for (i = 0; i < n_strings; ++i)
554 size_t cnt;
555 md5_buffer (string[i], strlen (string[i]), md5buffer);
557 for (cnt = 0; cnt < 16; ++cnt)
558 printf ("%02x", md5buffer[cnt]);
560 printf (" \"%s\"\n", string[i]);
563 else if (do_check)
565 if (optind + 1 < argc)
567 error (0, 0,
568 _("only one argument may be specified when using --check"));
569 usage (EXIT_FAILURE);
572 err = md5_check ((optind == argc) ? "-" : argv[optind]);
574 else
576 if (optind == argc)
577 argv[argc++] = "-";
579 for (; optind < argc; ++optind)
581 int fail;
582 char *file = argv[optind];
584 fail = md5_file (file, binary, md5buffer);
585 err |= fail;
586 if (!fail)
588 size_t i;
590 /* Output a leading backslash if the file name contains
591 a newline or backslash. */
592 if (strchr (file, '\n') || strchr (file, '\\'))
593 putchar ('\\');
595 for (i = 0; i < 16; ++i)
596 printf ("%02x", md5buffer[i]);
598 putchar (' ');
599 if (binary)
600 putchar ('*');
601 else
602 putchar (' ');
604 /* Translate each NEWLINE byte to the string, "\\n",
605 and each backslash to "\\\\". */
606 for (i = 0; i < strlen (file); ++i)
608 switch (file[i])
610 case '\n':
611 fputs ("\\n", stdout);
612 break;
614 case '\\':
615 fputs ("\\\\", stdout);
616 break;
618 default:
619 putchar (file[i]);
620 break;
623 putchar ('\n');
628 if (fclose (stdout) == EOF)
629 error (EXIT_FAILURE, errno, _("write error"));
631 if (have_read_stdin && fclose (stdin) == EOF)
632 error (EXIT_FAILURE, errno, _("standard input"));
634 exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);