(main): Standardize on the diagnostics given when someone gives
[platform/upstream/coreutils.git] / src / md5sum.c
1 /* Compute MD5 or SHA1 checksum of files or strings
2    Copyright (C) 1995-2004 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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.  */
17
18 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>.  */
19
20 #include <config.h>
21
22 #include <getopt.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25
26 #include "system.h"
27
28 #include "md5.h"
29 #include "sha1.h"
30 #include "checksum.h"
31 #include "getline.h"
32 #include "error.h"
33 #include "quote.h"
34
35 /* The official name of this program (e.g., no `g' prefix).  */
36 #define PROGRAM_NAME (algorithm == ALG_MD5 ? "md5sum" : "sha1sum")
37
38 #define AUTHORS "Ulrich Drepper", "Scott Miller"
39
40 /* Most systems do not distinguish between external and internal
41    text representations.  */
42 /* FIXME: This begs for an autoconf test.  */
43 #if O_BINARY
44 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
45 # define TEXT1TO1 "rb"
46 # define TEXTCNVT "r"
47 #else
48 # if defined VMS
49 #  define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
50 #  define TEXT1TO1 "rb", "ctx=stm"
51 #  define TEXTCNVT "r", "ctx=stm"
52 # else
53 #  if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
54 #   define OPENOPTS(BINARY) "r"
55 #  else
56     /* The following line is intended to evoke an error.
57        Using #error is not portable enough.  */
58     "Cannot determine system type."
59 #  endif
60 # endif
61 #endif
62
63
64 #define DIGEST_TYPE_STRING(Alg) ((Alg) == ALG_MD5 ? "MD5" : "SHA1")
65 #define DIGEST_STREAM(Alg) ((Alg) == ALG_MD5 ? md5_stream : sha_stream)
66
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)
70
71 #define MAX_DIGEST_BIN_BYTES MAX (DIGEST_BIN_BYTES (ALG_MD5), \
72                                   DIGEST_BIN_BYTES (ALG_SHA1))
73
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 */ )
80
81 /* Nonzero if any of the files read were the standard input. */
82 static int have_read_stdin;
83
84 /* The minimum length of a valid checksum line for the selected algorithm.  */
85 static size_t min_digest_line_length;
86
87 /* Set to the length of a digest hex string for the selected algorithm.  */
88 static size_t digest_hex_bytes;
89
90 /* With --check, don't generate any output.
91    The exit code indicates success or failure.  */
92 static int status_only = 0;
93
94 /* With --check, print a message to standard error warning about each
95    improperly formatted checksum line.  */
96 static int warn = 0;
97
98 /* Declared and set via one of the wrapper .c files.  */
99 /* int algorithm = ALG_UNSPECIFIED; */
100
101 /* The name this program was run with.  */
102 char *program_name;
103
104 static const struct option long_options[] =
105 {
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 },
114   { NULL, 0, NULL, 0 }
115 };
116
117 void
118 usage (int status)
119 {
120   if (status != EXIT_SUCCESS)
121     fprintf (stderr, _("Try `%s --help' for more information.\n"),
122              program_name);
123   else
124     {
125       printf (_("\
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\
130 "),
131               program_name, program_name,
132               DIGEST_TYPE_STRING (algorithm),
133               DIGEST_BITS (algorithm));
134       printf (_("\
135 \n\
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\
139 \n\
140 "),
141               DIGEST_TYPE_STRING (algorithm));
142       fputs (_("\
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\
146 \n\
147 "), stdout);
148       fputs (HELP_OPTION_DESCRIPTION, stdout);
149       fputs (VERSION_OPTION_DESCRIPTION, stdout);
150       printf (_("\
151 \n\
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);
158     }
159
160   exit (status);
161 }
162
163 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
164
165 /* Split the checksum string S (of length S_LEN) from a BSD 'md5' or
166    'sha1' command into two parts: a hexadecimal digest, and the file
167    name.  S is modified.  */
168
169 static int
170 bsd_split_3 (char *s, size_t s_len, unsigned char **hex_digest, char **file_name)
171 {
172   size_t i;
173
174   *file_name = s;
175
176   /* Find end of filename. The BSD 'md5' and 'sha1' commands do not escape
177      filenames, so search backwards for the last ')'. */
178   i = s_len - 1;
179   while (i && s[i] != ')')
180     i--;
181
182   if (s[i] != ')')
183     return 1;
184
185   s[i++] = '\0';
186
187   while (ISWHITE (s[i]))
188     i++;
189
190   if (s[i] != '=')
191     return 1;
192
193   i++;
194
195   while (ISWHITE (s[i]))
196     i++;
197
198   *hex_digest = (unsigned char *) &s[i];
199   return 0;
200 }
201
202 /* Split the string S (of length S_LEN) into three parts:
203    a hexadecimal digest, binary flag, and the file name.
204    S is modified.  */
205
206 static int
207 split_3 (char *s, size_t s_len,
208          unsigned char **hex_digest, int *binary, char **file_name)
209 {
210   size_t i;
211   int escaped_filename = 0;
212   size_t algo_name_len;
213
214   i = 0;
215   while (ISWHITE (s[i]))
216     ++i;
217
218   /* Check for BSD-style checksum line. */
219   algo_name_len = strlen (DIGEST_TYPE_STRING (algorithm));
220   if (strncmp (s + i, DIGEST_TYPE_STRING (algorithm), algo_name_len) == 0)
221     {
222       if (strncmp (s + i + algo_name_len, " (", 2) == 0)
223         {
224           *binary = 0;
225           return bsd_split_3 (s +      i + algo_name_len + 2,
226                               s_len - (i + algo_name_len + 2),
227                               hex_digest, file_name);
228         }
229     }
230
231   /* Ignore this line if it is too short.
232      Each line must have at least `min_digest_line_length - 1' (or one more, if
233      the first is a backslash) more characters to contain correct message digest
234      information.  */
235   if (s_len - i < min_digest_line_length + (s[i] == '\\'))
236     return 1;
237
238   if (s[i] == '\\')
239     {
240       ++i;
241       escaped_filename = 1;
242     }
243   *hex_digest = (unsigned char *) &s[i];
244
245   /* The first field has to be the n-character hexadecimal
246      representation of the message digest.  If it is not followed
247      immediately by a white space it's an error.  */
248   i += digest_hex_bytes;
249   if (!ISWHITE (s[i]))
250     return 1;
251
252   s[i++] = '\0';
253
254   if (s[i] != ' ' && s[i] != '*')
255     return 1;
256   *binary = (s[i++] == '*');
257
258   /* All characters between the type indicator and end of line are
259      significant -- that includes leading and trailing white space.  */
260   *file_name = &s[i];
261
262   if (escaped_filename)
263     {
264       /* Translate each `\n' string in the file name to a NEWLINE,
265          and each `\\' string to a backslash.  */
266
267       char *dst = &s[i];
268
269       while (i < s_len)
270         {
271           switch (s[i])
272             {
273             case '\\':
274               if (i == s_len - 1)
275                 {
276                   /* A valid line does not end with a backslash.  */
277                   return 1;
278                 }
279               ++i;
280               switch (s[i++])
281                 {
282                 case 'n':
283                   *dst++ = '\n';
284                   break;
285                 case '\\':
286                   *dst++ = '\\';
287                   break;
288                 default:
289                   /* Only `\' or `n' may follow a backslash.  */
290                   return 1;
291                 }
292               break;
293
294             case '\0':
295               /* The file name may not contain a NUL.  */
296               return 1;
297               break;
298
299             default:
300               *dst++ = s[i++];
301               break;
302             }
303         }
304       *dst = '\0';
305     }
306   return 0;
307 }
308
309 static int
310 hex_digits (unsigned char const *s)
311 {
312   while (*s)
313     {
314       if (!ISXDIGIT (*s))
315         return 0;
316       ++s;
317     }
318   return 1;
319 }
320
321 /* An interface to the function, DIGEST_STREAM,
322    (either md5_stream or sha_stream).
323    Operate on FILENAME (it may be "-") and put the result in *BIN_RESULT.
324    Return non-zero upon failure, zero to indicate success.  */
325
326 static int
327 digest_file (const char *filename, int binary, unsigned char *bin_result,
328            int (*digest_stream)(FILE *, void *))
329 {
330   FILE *fp;
331   int err;
332
333   if (STREQ (filename, "-"))
334     {
335       have_read_stdin = 1;
336       fp = stdin;
337 #if O_BINARY
338       /* If we need binary reads from a pipe or redirected stdin, we need
339          to switch it to BINARY mode here, since stdin is already open.  */
340       if (binary)
341         SET_BINARY (fileno (stdin));
342 #endif
343     }
344   else
345     {
346       /* OPENOPTS is a macro.  It varies with the system.
347          Some systems distinguish between internal and
348          external text representations.  */
349
350       fp = fopen (filename, OPENOPTS (binary));
351       if (fp == NULL)
352         {
353           error (0, errno, "%s", filename);
354           return 1;
355         }
356     }
357
358   err = (*digest_stream) (fp, bin_result);
359   if (err)
360     {
361       error (0, errno, "%s", filename);
362       if (fp != stdin)
363         fclose (fp);
364       return 1;
365     }
366
367   if (fp != stdin && fclose (fp) == EOF)
368     {
369       error (0, errno, "%s", filename);
370       return 1;
371     }
372
373   return 0;
374 }
375
376 static int
377 digest_check (const char *checkfile_name, int (*digest_stream)(FILE *, void *))
378 {
379   FILE *checkfile_stream;
380   int n_properly_formated_lines = 0;
381   int n_mismatched_checksums = 0;
382   int n_open_or_read_failures = 0;
383   unsigned char bin_buffer[MAX_DIGEST_BIN_BYTES];
384   size_t line_number;
385   char *line;
386   size_t line_chars_allocated;
387
388   if (STREQ (checkfile_name, "-"))
389     {
390       have_read_stdin = 1;
391       checkfile_name = _("standard input");
392       checkfile_stream = stdin;
393     }
394   else
395     {
396       checkfile_stream = fopen (checkfile_name, "r");
397       if (checkfile_stream == NULL)
398         {
399           error (0, errno, "%s", checkfile_name);
400           return 1;
401         }
402     }
403
404   SET_MODE (fileno (checkfile_stream), O_TEXT);
405   line_number = 0;
406   line = NULL;
407   line_chars_allocated = 0;
408   do
409     {
410       char *filename;
411       int binary;
412       unsigned char *hex_digest;
413       int err;
414       int line_length;
415
416       ++line_number;
417
418       line_length = getline (&line, &line_chars_allocated, checkfile_stream);
419       if (line_length <= 0)
420         break;
421
422       /* Ignore comment lines, which begin with a '#' character.  */
423       if (line[0] == '#')
424         continue;
425
426       /* Remove any trailing newline.  */
427       if (line[line_length - 1] == '\n')
428         line[--line_length] = '\0';
429
430       err = split_3 (line, line_length, &hex_digest, &binary, &filename);
431       if (err || !hex_digits (hex_digest))
432         {
433           if (warn)
434             {
435               error (0, 0,
436                      _("%s: %lu: improperly formatted %s checksum line"),
437                      checkfile_name, (unsigned long) line_number,
438                      DIGEST_TYPE_STRING (algorithm));
439             }
440         }
441       else
442         {
443           static const char bin2hex[] = { '0', '1', '2', '3',
444                                           '4', '5', '6', '7',
445                                           '8', '9', 'a', 'b',
446                                           'c', 'd', 'e', 'f' };
447           int fail;
448
449           ++n_properly_formated_lines;
450
451           fail = digest_file (filename, binary, bin_buffer, digest_stream);
452
453           if (fail)
454             {
455               ++n_open_or_read_failures;
456               if (!status_only)
457                 {
458                   printf (_("%s: FAILED open or read\n"), filename);
459                   fflush (stdout);
460                 }
461             }
462           else
463             {
464               size_t digest_bin_bytes = digest_hex_bytes / 2;
465               size_t cnt;
466               /* Compare generated binary number with text representation
467                  in check file.  Ignore case of hex digits.  */
468               for (cnt = 0; cnt < digest_bin_bytes; ++cnt)
469                 {
470                   if (TOLOWER (hex_digest[2 * cnt])
471                       != bin2hex[bin_buffer[cnt] >> 4]
472                       || (TOLOWER (hex_digest[2 * cnt + 1])
473                           != (bin2hex[bin_buffer[cnt] & 0xf])))
474                     break;
475                 }
476               if (cnt != digest_bin_bytes)
477                 ++n_mismatched_checksums;
478
479               if (!status_only)
480                 {
481                   printf ("%s: %s\n", filename,
482                           (cnt != digest_bin_bytes ? _("FAILED") : _("OK")));
483                   fflush (stdout);
484                 }
485             }
486         }
487     }
488   while (!feof (checkfile_stream) && !ferror (checkfile_stream));
489
490   if (line)
491     free (line);
492
493   if (ferror (checkfile_stream))
494     {
495       error (0, 0, _("%s: read error"), checkfile_name);
496       return 1;
497     }
498
499   if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
500     {
501       error (0, errno, "%s", checkfile_name);
502       return 1;
503     }
504
505   if (n_properly_formated_lines == 0)
506     {
507       /* Warn if no tests are found.  */
508       error (0, 0, _("%s: no properly formatted %s checksum lines found"),
509              checkfile_name, DIGEST_TYPE_STRING (algorithm));
510     }
511   else
512     {
513       if (!status_only)
514         {
515           int n_computed_checkums = (n_properly_formated_lines
516                                      - n_open_or_read_failures);
517
518           if (n_open_or_read_failures > 0)
519             {
520               error (0, 0,
521                      _("WARNING: %d of %d listed %s could not be read"),
522                      n_open_or_read_failures, n_properly_formated_lines,
523                      (n_properly_formated_lines == 1
524                       ? _("file") : _("files")));
525             }
526
527           if (n_mismatched_checksums > 0)
528             {
529               error (0, 0,
530                    _("WARNING: %d of %d computed %s did NOT match"),
531                      n_mismatched_checksums, n_computed_checkums,
532                      (n_computed_checkums == 1
533                       ? _("checksum") : _("checksums")));
534             }
535         }
536     }
537
538   return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
539            && n_open_or_read_failures == 0) ? 0 : 1);
540 }
541
542 int
543 main (int argc, char **argv)
544 {
545   unsigned char bin_buffer[MAX_DIGEST_BIN_BYTES];
546   int do_check = 0;
547   int opt;
548   char **string = NULL;
549   size_t n_strings = 0;
550   int err = 0;
551   int file_type_specified = 0;
552
553 #if O_BINARY
554   /* Binary is default on MSDOS, so the actual file contents
555      are used in computation.  */
556   int binary = 1;
557 #else
558   /* Text is default of the Plumb/Lankester format.  */
559   int binary = 0;
560 #endif
561
562   /* Setting values of global variables.  */
563   initialize_main (&argc, &argv);
564   program_name = argv[0];
565   setlocale (LC_ALL, "");
566   bindtextdomain (PACKAGE, LOCALEDIR);
567   textdomain (PACKAGE);
568
569   atexit (close_stdout);
570
571   while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
572     switch (opt)
573       {
574       case 0:                   /* long option */
575         break;
576       case 1: /* --string */
577         {
578           if (string == NULL)
579             string = xnmalloc (argc - 1, sizeof *string);
580
581           if (optarg == NULL)
582             optarg = "";
583           string[n_strings++] = optarg;
584         }
585         break;
586       case 'b':
587         file_type_specified = 1;
588         binary = 1;
589         break;
590       case 'c':
591         do_check = 1;
592         break;
593       case 2:
594         status_only = 1;
595         warn = 0;
596         break;
597       case 't':
598         file_type_specified = 1;
599         binary = 0;
600         break;
601       case 'w':
602         status_only = 0;
603         warn = 1;
604         break;
605       case_GETOPT_HELP_CHAR;
606       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
607       default:
608         usage (EXIT_FAILURE);
609       }
610
611   min_digest_line_length = MIN_DIGEST_LINE_LENGTH (algorithm);
612   digest_hex_bytes = DIGEST_HEX_BYTES (algorithm);
613
614   if (file_type_specified && do_check)
615     {
616       error (0, 0, _("the --binary and --text options are meaningless when \
617 verifying checksums"));
618       usage (EXIT_FAILURE);
619     }
620
621   if (n_strings > 0 && do_check)
622     {
623       error (0, 0,
624              _("the --string and --check options are mutually exclusive"));
625       usage (EXIT_FAILURE);
626     }
627
628   if (status_only && !do_check)
629     {
630       error (0, 0,
631        _("the --status option is meaningful only when verifying checksums"));
632       usage (EXIT_FAILURE);
633     }
634
635   if (warn && !do_check)
636     {
637       error (0, 0,
638        _("the --warn option is meaningful only when verifying checksums"));
639       usage (EXIT_FAILURE);
640     }
641
642   if (n_strings > 0)
643     {
644       size_t i;
645
646       if (optind < argc)
647         {
648           error (0, 0, _("extra operand %s"), quote (argv[optind]));
649           fprintf (stderr, "%s\n",
650                    _("File operands cannot be combined with --string."));
651           usage (EXIT_FAILURE);
652         }
653       for (i = 0; i < n_strings; ++i)
654         {
655           size_t cnt;
656           if (algorithm == ALG_MD5)
657             md5_buffer (string[i], strlen (string[i]), bin_buffer);
658           else
659             sha_buffer (string[i], strlen (string[i]), bin_buffer);
660
661           for (cnt = 0; cnt < (digest_hex_bytes / 2); ++cnt)
662             printf ("%02x", bin_buffer[cnt]);
663
664           printf ("  \"%s\"\n", string[i]);
665         }
666     }
667   else if (do_check)
668     {
669       if (optind + 1 < argc)
670         {
671           error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
672           fprintf (stderr, "%s\n",
673                    _("Only one operand may be specified when using --check."));
674           usage (EXIT_FAILURE);
675         }
676
677       err = digest_check ((optind == argc) ? "-" : argv[optind],
678                           DIGEST_STREAM (algorithm));
679     }
680   else
681     {
682       if (optind == argc)
683         argv[argc++] = "-";
684
685       for (; optind < argc; ++optind)
686         {
687           int fail;
688           char *file = argv[optind];
689
690           fail = digest_file (file, binary, bin_buffer,
691                               DIGEST_STREAM (algorithm));
692           err |= fail;
693           if (!fail)
694             {
695               size_t i;
696
697               /* Output a leading backslash if the file name contains
698                  a newline or backslash.  */
699               if (strchr (file, '\n') || strchr (file, '\\'))
700                 putchar ('\\');
701
702               for (i = 0; i < (digest_hex_bytes / 2); ++i)
703                 printf ("%02x", bin_buffer[i]);
704
705               putchar (' ');
706               if (binary)
707                 putchar ('*');
708               else
709                 putchar (' ');
710
711               /* Translate each NEWLINE byte to the string, "\\n",
712                  and each backslash to "\\\\".  */
713               for (i = 0; i < strlen (file); ++i)
714                 {
715                   switch (file[i])
716                     {
717                     case '\n':
718                       fputs ("\\n", stdout);
719                       break;
720
721                     case '\\':
722                       fputs ("\\\\", stdout);
723                       break;
724
725                     default:
726                       putchar (file[i]);
727                       break;
728                     }
729                 }
730               putchar ('\n');
731             }
732         }
733     }
734
735   if (have_read_stdin && fclose (stdin) == EOF)
736     error (EXIT_FAILURE, errno, _("standard input"));
737
738   exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
739 }