dd: clarify meaning of multiplication factors; put xM in order
[platform/upstream/coreutils.git] / src / md5sum.c
1 /* Compute MD5, SHA1, SHA224, SHA256, SHA384 or SHA512 checksum of files or strings
2    Copyright (C) 1995-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>.  */
18
19 #include <config.h>
20
21 #include <getopt.h>
22 #include <sys/types.h>
23
24 #include "system.h"
25
26 #if HASH_ALGO_MD5
27 # include "md5.h"
28 #endif
29 #if HASH_ALGO_SHA1
30 # include "sha1.h"
31 #endif
32 #if HASH_ALGO_SHA256 || HASH_ALGO_SHA224
33 # include "sha256.h"
34 #endif
35 #if HASH_ALGO_SHA512 || HASH_ALGO_SHA384
36 # include "sha512.h"
37 #endif
38 #include "error.h"
39 #include "stdio--.h"
40
41 /* The official name of this program (e.g., no `g' prefix).  */
42 #if HASH_ALGO_MD5
43 # define PROGRAM_NAME "md5sum"
44 # define DIGEST_TYPE_STRING "MD5"
45 # define DIGEST_STREAM md5_stream
46 # define DIGEST_BITS 128
47 # define DIGEST_REFERENCE "RFC 1321"
48 # define DIGEST_ALIGN 4
49 #elif HASH_ALGO_SHA1
50 # define PROGRAM_NAME "sha1sum"
51 # define DIGEST_TYPE_STRING "SHA1"
52 # define DIGEST_STREAM sha1_stream
53 # define DIGEST_BITS 160
54 # define DIGEST_REFERENCE "FIPS-180-1"
55 # define DIGEST_ALIGN 4
56 #elif HASH_ALGO_SHA256
57 # define PROGRAM_NAME "sha256sum"
58 # define DIGEST_TYPE_STRING "SHA256"
59 # define DIGEST_STREAM sha256_stream
60 # define DIGEST_BITS 256
61 # define DIGEST_REFERENCE "FIPS-180-2"
62 # define DIGEST_ALIGN 4
63 #elif HASH_ALGO_SHA224
64 # define PROGRAM_NAME "sha224sum"
65 # define DIGEST_TYPE_STRING "SHA224"
66 # define DIGEST_STREAM sha224_stream
67 # define DIGEST_BITS 224
68 # define DIGEST_REFERENCE "RFC 3874"
69 # define DIGEST_ALIGN 4
70 #elif HASH_ALGO_SHA512
71 # define PROGRAM_NAME "sha512sum"
72 # define DIGEST_TYPE_STRING "SHA512"
73 # define DIGEST_STREAM sha512_stream
74 # define DIGEST_BITS 512
75 # define DIGEST_REFERENCE "FIPS-180-2"
76 # define DIGEST_ALIGN 8
77 #elif HASH_ALGO_SHA384
78 # define PROGRAM_NAME "sha384sum"
79 # define DIGEST_TYPE_STRING "SHA384"
80 # define DIGEST_STREAM sha384_stream
81 # define DIGEST_BITS 384
82 # define DIGEST_REFERENCE "FIPS-180-2"
83 # define DIGEST_ALIGN 8
84 #else
85 # error "Can't decide which hash algorithm to compile."
86 #endif
87
88 #define DIGEST_HEX_BYTES (DIGEST_BITS / 4)
89 #define DIGEST_BIN_BYTES (DIGEST_BITS / 8)
90
91 #define AUTHORS \
92   proper_name ("Ulrich Drepper"), \
93   proper_name ("Scott Miller"), \
94   proper_name ("David Madore")
95
96 /* The minimum length of a valid digest line.  This length does
97    not include any newline character at the end of a line.  */
98 #define MIN_DIGEST_LINE_LENGTH \
99   (DIGEST_HEX_BYTES /* length of hexadecimal message digest */ \
100    + 2 /* blank and binary indicator */ \
101    + 1 /* minimum filename length */ )
102
103 /* True if any of the files read were the standard input. */
104 static bool have_read_stdin;
105
106 /* The minimum length of a valid checksum line for the selected algorithm.  */
107 static size_t min_digest_line_length;
108
109 /* Set to the length of a digest hex string for the selected algorithm.  */
110 static size_t digest_hex_bytes;
111
112 /* With --check, don't generate any output.
113    The exit code indicates success or failure.  */
114 static bool status_only = false;
115
116 /* With --check, print a message to standard error warning about each
117    improperly formatted checksum line.  */
118 static bool warn = false;
119
120 /* With --check, suppress the "OK" printed for each verified file.  */
121 static bool quiet = false;
122
123 /* For long options that have no equivalent short option, use a
124    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
125 enum
126 {
127   STATUS_OPTION = CHAR_MAX + 1,
128   QUIET_OPTION
129 };
130
131 static struct option const long_options[] =
132 {
133   { "binary", no_argument, NULL, 'b' },
134   { "check", no_argument, NULL, 'c' },
135   { "quiet", no_argument, NULL, QUIET_OPTION },
136   { "status", no_argument, NULL, STATUS_OPTION },
137   { "text", no_argument, NULL, 't' },
138   { "warn", no_argument, NULL, 'w' },
139   { GETOPT_HELP_OPTION_DECL },
140   { GETOPT_VERSION_OPTION_DECL },
141   { NULL, 0, NULL, 0 }
142 };
143
144 void
145 usage (int status)
146 {
147   if (status != EXIT_SUCCESS)
148     fprintf (stderr, _("Try `%s --help' for more information.\n"),
149              program_name);
150   else
151     {
152       printf (_("\
153 Usage: %s [OPTION]... [FILE]...\n\
154 Print or check %s (%d-bit) checksums.\n\
155 With no FILE, or when FILE is -, read standard input.\n\
156 \n\
157 "),
158               program_name,
159               DIGEST_TYPE_STRING,
160               DIGEST_BITS);
161       if (O_BINARY)
162         fputs (_("\
163   -b, --binary            read in binary mode (default unless reading tty stdin)\n\
164 "), stdout);
165       else
166         fputs (_("\
167   -b, --binary            read in binary mode\n\
168 "), stdout);
169       printf (_("\
170   -c, --check             read %s sums from the FILEs and check them\n"),
171               DIGEST_TYPE_STRING);
172       if (O_BINARY)
173         fputs (_("\
174   -t, --text              read in text mode (default if reading tty stdin)\n\
175 "), stdout);
176       else
177         fputs (_("\
178   -t, --text              read in text mode (default)\n\
179 "), stdout);
180       fputs (_("\
181 \n\
182 The following three options are useful only when verifying checksums:\n\
183       --quiet             don't print OK for each successfully verified file\n\
184       --status            don't output anything, status code shows success\n\
185   -w, --warn              warn about improperly formatted checksum lines\n\
186 \n\
187 "), stdout);
188       fputs (HELP_OPTION_DESCRIPTION, stdout);
189       fputs (VERSION_OPTION_DESCRIPTION, stdout);
190       printf (_("\
191 \n\
192 The sums are computed as described in %s.  When checking, the input\n\
193 should be a former output of this program.  The default mode is to print\n\
194 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
195 text), and name for each FILE.\n"),
196               DIGEST_REFERENCE);
197       emit_bug_reporting_address ();
198     }
199
200   exit (status);
201 }
202
203 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
204
205 /* Split the checksum string S (of length S_LEN) from a BSD 'md5' or
206    'sha1' command into two parts: a hexadecimal digest, and the file
207    name.  S is modified.  Return true if successful.  */
208
209 static bool
210 bsd_split_3 (char *s, size_t s_len, unsigned char **hex_digest, char **file_name)
211 {
212   size_t i;
213
214   if (s_len == 0)
215     return false;
216
217   *file_name = s;
218
219   /* Find end of filename. The BSD 'md5' and 'sha1' commands do not escape
220      filenames, so search backwards for the last ')'. */
221   i = s_len - 1;
222   while (i && s[i] != ')')
223     i--;
224
225   if (s[i] != ')')
226     return false;
227
228   s[i++] = '\0';
229
230   while (ISWHITE (s[i]))
231     i++;
232
233   if (s[i] != '=')
234     return false;
235
236   i++;
237
238   while (ISWHITE (s[i]))
239     i++;
240
241   *hex_digest = (unsigned char *) &s[i];
242   return true;
243 }
244
245 /* Split the string S (of length S_LEN) into three parts:
246    a hexadecimal digest, binary flag, and the file name.
247    S is modified.  Return true if successful.  */
248
249 static bool
250 split_3 (char *s, size_t s_len,
251          unsigned char **hex_digest, int *binary, char **file_name)
252 {
253   size_t i;
254   bool escaped_filename = false;
255   size_t algo_name_len;
256
257   i = 0;
258   while (ISWHITE (s[i]))
259     ++i;
260
261   /* Check for BSD-style checksum line. */
262   algo_name_len = strlen (DIGEST_TYPE_STRING);
263   if (strncmp (s + i, DIGEST_TYPE_STRING, algo_name_len) == 0)
264     {
265       if (strncmp (s + i + algo_name_len, " (", 2) == 0)
266         {
267           *binary = 0;
268           return bsd_split_3 (s +      i + algo_name_len + 2,
269                               s_len - (i + algo_name_len + 2),
270                               hex_digest, file_name);
271         }
272     }
273
274   /* Ignore this line if it is too short.
275      Each line must have at least `min_digest_line_length - 1' (or one more, if
276      the first is a backslash) more characters to contain correct message digest
277      information.  */
278   if (s_len - i < min_digest_line_length + (s[i] == '\\'))
279     return false;
280
281   if (s[i] == '\\')
282     {
283       ++i;
284       escaped_filename = true;
285     }
286   *hex_digest = (unsigned char *) &s[i];
287
288   /* The first field has to be the n-character hexadecimal
289      representation of the message digest.  If it is not followed
290      immediately by a white space it's an error.  */
291   i += digest_hex_bytes;
292   if (!ISWHITE (s[i]))
293     return false;
294
295   s[i++] = '\0';
296
297   if (s[i] != ' ' && s[i] != '*')
298     return false;
299   *binary = (s[i++] == '*');
300
301   /* All characters between the type indicator and end of line are
302      significant -- that includes leading and trailing white space.  */
303   *file_name = &s[i];
304
305   if (escaped_filename)
306     {
307       /* Translate each `\n' string in the file name to a NEWLINE,
308          and each `\\' string to a backslash.  */
309
310       char *dst = &s[i];
311
312       while (i < s_len)
313         {
314           switch (s[i])
315             {
316             case '\\':
317               if (i == s_len - 1)
318                 {
319                   /* A valid line does not end with a backslash.  */
320                   return false;
321                 }
322               ++i;
323               switch (s[i++])
324                 {
325                 case 'n':
326                   *dst++ = '\n';
327                   break;
328                 case '\\':
329                   *dst++ = '\\';
330                   break;
331                 default:
332                   /* Only `\' or `n' may follow a backslash.  */
333                   return false;
334                 }
335               break;
336
337             case '\0':
338               /* The file name may not contain a NUL.  */
339               return false;
340               break;
341
342             default:
343               *dst++ = s[i++];
344               break;
345             }
346         }
347       *dst = '\0';
348     }
349   return true;
350 }
351
352 /* Return true if S is a NUL-terminated string of DIGEST_HEX_BYTES hex digits.
353    Otherwise, return false.  */
354 static bool
355 hex_digits (unsigned char const *s)
356 {
357   unsigned int i;
358   for (i = 0; i < digest_hex_bytes; i++)
359     {
360       if (!isxdigit (*s))
361         return false;
362       ++s;
363     }
364   return *s == '\0';
365 }
366
367 /* An interface to the function, DIGEST_STREAM.
368    Operate on FILENAME (it may be "-").
369
370    *BINARY indicates whether the file is binary.  BINARY < 0 means it
371    depends on whether binary mode makes any difference and the file is
372    a terminal; in that case, clear *BINARY if the file was treated as
373    text because it was a terminal.
374
375    Put the checksum in *BIN_RESULT, which must be properly aligned.
376    Return true if successful.  */
377
378 static bool
379 digest_file (const char *filename, int *binary, unsigned char *bin_result)
380 {
381   FILE *fp;
382   int err;
383   bool is_stdin = STREQ (filename, "-");
384
385   if (is_stdin)
386     {
387       have_read_stdin = true;
388       fp = stdin;
389       if (O_BINARY && *binary)
390         {
391           if (*binary < 0)
392             *binary = ! isatty (STDIN_FILENO);
393           if (*binary)
394             freopen (NULL, "rb", stdin);
395         }
396     }
397   else
398     {
399       fp = fopen (filename, (O_BINARY && *binary ? "rb" : "r"));
400       if (fp == NULL)
401         {
402           error (0, errno, "%s", filename);
403           return false;
404         }
405     }
406
407   err = DIGEST_STREAM (fp, bin_result);
408   if (err)
409     {
410       error (0, errno, "%s", filename);
411       if (fp != stdin)
412         fclose (fp);
413       return false;
414     }
415
416   if (!is_stdin && fclose (fp) != 0)
417     {
418       error (0, errno, "%s", filename);
419       return false;
420     }
421
422   return true;
423 }
424
425 static bool
426 digest_check (const char *checkfile_name)
427 {
428   FILE *checkfile_stream;
429   uintmax_t n_properly_formatted_lines = 0;
430   uintmax_t n_mismatched_checksums = 0;
431   uintmax_t n_open_or_read_failures = 0;
432   unsigned char bin_buffer_unaligned[DIGEST_BIN_BYTES + DIGEST_ALIGN];
433   /* Make sure bin_buffer is properly aligned. */
434   unsigned char *bin_buffer = ptr_align (bin_buffer_unaligned, DIGEST_ALIGN);
435   uintmax_t line_number;
436   char *line;
437   size_t line_chars_allocated;
438   bool is_stdin = STREQ (checkfile_name, "-");
439
440   if (is_stdin)
441     {
442       have_read_stdin = true;
443       checkfile_name = _("standard input");
444       checkfile_stream = stdin;
445     }
446   else
447     {
448       checkfile_stream = fopen (checkfile_name, "r");
449       if (checkfile_stream == NULL)
450         {
451           error (0, errno, "%s", checkfile_name);
452           return false;
453         }
454     }
455
456   line_number = 0;
457   line = NULL;
458   line_chars_allocated = 0;
459   do
460     {
461       char *filename IF_LINT (= NULL);
462       int binary;
463       unsigned char *hex_digest IF_LINT (= NULL);
464       ssize_t line_length;
465
466       ++line_number;
467       if (line_number == 0)
468         error (EXIT_FAILURE, 0, _("%s: too many checksum lines"),
469                checkfile_name);
470
471       line_length = getline (&line, &line_chars_allocated, checkfile_stream);
472       if (line_length <= 0)
473         break;
474
475       /* Ignore comment lines, which begin with a '#' character.  */
476       if (line[0] == '#')
477         continue;
478
479       /* Remove any trailing newline.  */
480       if (line[line_length - 1] == '\n')
481         line[--line_length] = '\0';
482
483       if (! (split_3 (line, line_length, &hex_digest, &binary, &filename)
484              && ! (is_stdin && STREQ (filename, "-"))
485              && hex_digits (hex_digest)))
486         {
487           if (warn)
488             {
489               error (0, 0,
490                      _("%s: %" PRIuMAX
491                        ": improperly formatted %s checksum line"),
492                      checkfile_name, line_number,
493                      DIGEST_TYPE_STRING);
494             }
495         }
496       else
497         {
498           static const char bin2hex[] = { '0', '1', '2', '3',
499                                           '4', '5', '6', '7',
500                                           '8', '9', 'a', 'b',
501                                           'c', 'd', 'e', 'f' };
502           bool ok;
503
504           ++n_properly_formatted_lines;
505
506           ok = digest_file (filename, &binary, bin_buffer);
507
508           if (!ok)
509             {
510               ++n_open_or_read_failures;
511               if (!status_only)
512                 {
513                   printf (_("%s: FAILED open or read\n"), filename);
514                   fflush (stdout);
515                 }
516             }
517           else
518             {
519               size_t digest_bin_bytes = digest_hex_bytes / 2;
520               size_t cnt;
521               /* Compare generated binary number with text representation
522                  in check file.  Ignore case of hex digits.  */
523               for (cnt = 0; cnt < digest_bin_bytes; ++cnt)
524                 {
525                   if (tolower (hex_digest[2 * cnt])
526                       != bin2hex[bin_buffer[cnt] >> 4]
527                       || (tolower (hex_digest[2 * cnt + 1])
528                           != (bin2hex[bin_buffer[cnt] & 0xf])))
529                     break;
530                 }
531               if (cnt != digest_bin_bytes)
532                 ++n_mismatched_checksums;
533
534               if (!status_only)
535                 {
536                   if (cnt != digest_bin_bytes)
537                     printf ("%s: %s\n", filename, _("FAILED"));
538                   else if (!quiet)
539                     printf ("%s: %s\n", filename, _("OK"));
540                   fflush (stdout);
541                 }
542             }
543         }
544     }
545   while (!feof (checkfile_stream) && !ferror (checkfile_stream));
546
547   free (line);
548
549   if (ferror (checkfile_stream))
550     {
551       error (0, 0, _("%s: read error"), checkfile_name);
552       return false;
553     }
554
555   if (!is_stdin && fclose (checkfile_stream) != 0)
556     {
557       error (0, errno, "%s", checkfile_name);
558       return false;
559     }
560
561   if (n_properly_formatted_lines == 0)
562     {
563       /* Warn if no tests are found.  */
564       error (0, 0, _("%s: no properly formatted %s checksum lines found"),
565              checkfile_name, DIGEST_TYPE_STRING);
566     }
567   else
568     {
569       if (!status_only)
570         {
571           if (n_open_or_read_failures != 0)
572             error (0, 0,
573                    ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX
574                              " listed file could not be read",
575                              "WARNING: %" PRIuMAX " of %" PRIuMAX
576                              " listed files could not be read",
577                              select_plural (n_properly_formatted_lines)),
578                    n_open_or_read_failures, n_properly_formatted_lines);
579
580           if (n_mismatched_checksums != 0)
581             {
582               uintmax_t n_computed_checksums =
583                 (n_properly_formatted_lines - n_open_or_read_failures);
584               error (0, 0,
585                      ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX
586                                " computed checksum did NOT match",
587                                "WARNING: %" PRIuMAX " of %" PRIuMAX
588                                " computed checksums did NOT match",
589                                select_plural (n_computed_checksums)),
590                      n_mismatched_checksums, n_computed_checksums);
591             }
592         }
593     }
594
595   return (n_properly_formatted_lines != 0
596           && n_mismatched_checksums == 0
597           && n_open_or_read_failures == 0);
598 }
599
600 int
601 main (int argc, char **argv)
602 {
603   unsigned char bin_buffer_unaligned[DIGEST_BIN_BYTES + DIGEST_ALIGN];
604   /* Make sure bin_buffer is properly aligned. */
605   unsigned char *bin_buffer = ptr_align (bin_buffer_unaligned, DIGEST_ALIGN);
606   bool do_check = false;
607   int opt;
608   bool ok = true;
609   int binary = -1;
610
611   /* Setting values of global variables.  */
612   initialize_main (&argc, &argv);
613   set_program_name (argv[0]);
614   setlocale (LC_ALL, "");
615   bindtextdomain (PACKAGE, LOCALEDIR);
616   textdomain (PACKAGE);
617
618   atexit (close_stdout);
619
620   while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
621     switch (opt)
622       {
623       case 'b':
624         binary = 1;
625         break;
626       case 'c':
627         do_check = true;
628         break;
629       case STATUS_OPTION:
630         status_only = true;
631         warn = false;
632         quiet = false;
633         break;
634       case 't':
635         binary = 0;
636         break;
637       case 'w':
638         status_only = false;
639         warn = true;
640         quiet = false;
641         break;
642       case QUIET_OPTION:
643         status_only = false;
644         warn = false;
645         quiet = true;
646         break;
647       case_GETOPT_HELP_CHAR;
648       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
649       default:
650         usage (EXIT_FAILURE);
651       }
652
653   min_digest_line_length = MIN_DIGEST_LINE_LENGTH;
654   digest_hex_bytes = DIGEST_HEX_BYTES;
655
656   if (0 <= binary && do_check)
657     {
658       error (0, 0, _("the --binary and --text options are meaningless when "
659                      "verifying checksums"));
660       usage (EXIT_FAILURE);
661     }
662
663   if (status_only & !do_check)
664     {
665       error (0, 0,
666        _("the --status option is meaningful only when verifying checksums"));
667       usage (EXIT_FAILURE);
668     }
669
670   if (warn & !do_check)
671     {
672       error (0, 0,
673        _("the --warn option is meaningful only when verifying checksums"));
674       usage (EXIT_FAILURE);
675     }
676
677   if (quiet & !do_check)
678     {
679       error (0, 0,
680        _("the --quiet option is meaningful only when verifying checksums"));
681       usage (EXIT_FAILURE);
682     }
683
684   if (!O_BINARY && binary < 0)
685     binary = 0;
686
687   if (optind == argc)
688     argv[argc++] = "-";
689
690   for (; optind < argc; ++optind)
691     {
692       char *file = argv[optind];
693
694       if (do_check)
695         ok &= digest_check (file);
696       else
697         {
698           int file_is_binary = binary;
699
700           if (! digest_file (file, &file_is_binary, bin_buffer))
701             ok = false;
702           else
703             {
704               size_t i;
705
706               /* Output a leading backslash if the file name contains
707                  a newline or backslash.  */
708               if (strchr (file, '\n') || strchr (file, '\\'))
709                 putchar ('\\');
710
711               for (i = 0; i < (digest_hex_bytes / 2); ++i)
712                 printf ("%02x", bin_buffer[i]);
713
714               putchar (' ');
715               if (file_is_binary)
716                 putchar ('*');
717               else
718                 putchar (' ');
719
720               /* Translate each NEWLINE byte to the string, "\\n",
721                  and each backslash to "\\\\".  */
722               for (i = 0; i < strlen (file); ++i)
723                 {
724                   switch (file[i])
725                     {
726                     case '\n':
727                       fputs ("\\n", stdout);
728                       break;
729
730                     case '\\':
731                       fputs ("\\\\", stdout);
732                       break;
733
734                     default:
735                       putchar (file[i]);
736                       break;
737                     }
738                 }
739               putchar ('\n');
740             }
741         }
742     }
743
744   if (have_read_stdin && fclose (stdin) == EOF)
745     error (EXIT_FAILURE, errno, _("standard input"));
746
747   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
748 }