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