33eb385312287db768726a645775bdccf50da57d
[platform/upstream/coreutils.git] / src / md5sum.c
1 /* Compute MD5 or SHA1 checksum of files or strings
2    Copyright (C) 1995-2001 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 "sha.h"
30 #include "checksum.h"
31 #include "getline.h"
32 #include "closeout.h"
33 #include "error.h"
34
35 /* The official name of this program (e.g., no `g' prefix).  */
36 #define PROGRAM_NAME (algorithm == ALG_MD5 ? "md5sum" : "shasum")
37
38 #define AUTHORS N_ ("Ulrich Drepper and 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 int 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 != 0)
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       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
158     }
159
160   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
161 }
162
163 static int
164 split_3 (char *s, size_t s_len, unsigned char **u, int *binary, char **w)
165 {
166   size_t i;
167   int escaped_filename = 0;
168
169 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
170
171   i = 0;
172   while (ISWHITE (s[i]))
173     ++i;
174
175   /* The line must have at least `min_digest_line_length - 1' (or one more, if
176      the first is a backslash) more characters to contain correct message digest
177      information.  Ignore this line if it is too short.  */
178   if (!(s_len - i >= min_digest_line_length
179         || (s[i] == '\\' && s_len - i >= 1 + min_digest_line_length)))
180     return 1;
181
182   if (s[i] == '\\')
183     {
184       ++i;
185       escaped_filename = 1;
186     }
187   *u = (unsigned char *) &s[i];
188
189   /* The first field has to be the n-character hexadecimal
190      representation of the message digest.  If it is not followed
191      immediately by a white space it's an error.  */
192   i += digest_hex_bytes;
193   if (!ISWHITE (s[i]))
194     return 1;
195
196   s[i++] = '\0';
197
198   if (s[i] != ' ' && s[i] != '*')
199     return 1;
200   *binary = (s[i++] == '*');
201
202   /* All characters between the type indicator and end of line are
203      significant -- that includes leading and trailing white space.  */
204   *w = &s[i];
205
206   if (escaped_filename)
207     {
208       /* Translate each `\n' string in the file name to a NEWLINE,
209          and each `\\' string to a backslash.  */
210
211       char *dst = &s[i];
212
213       while (i < s_len)
214         {
215           switch (s[i])
216             {
217             case '\\':
218               if (i == s_len - 1)
219                 {
220                   /* A valid line does not end with a backslash.  */
221                   return 1;
222                 }
223               ++i;
224               switch (s[i++])
225                 {
226                 case 'n':
227                   *dst++ = '\n';
228                   break;
229                 case '\\':
230                   *dst++ = '\\';
231                   break;
232                 default:
233                   /* Only `\' or `n' may follow a backslash.  */
234                   return 1;
235                 }
236               break;
237
238             case '\0':
239               /* The file name may not contain a NUL.  */
240               return 1;
241               break;
242
243             default:
244               *dst++ = s[i++];
245               break;
246             }
247         }
248       *dst = '\0';
249     }
250   return 0;
251 }
252
253 static int
254 hex_digits (unsigned char const *s)
255 {
256   while (*s)
257     {
258       if (!ISXDIGIT (*s))
259         return 0;
260       ++s;
261     }
262   return 1;
263 }
264
265 /* An interface to the function, DIGEST_STREAM, (either md5_stream or sha_stream).
266    Operate on FILENAME (it may be "-") and put the result in *BIN_RESULT.
267    Return non-zero upon failure, zero to indicate success.  */
268
269 static int
270 digest_file (const char *filename, int binary, unsigned char *bin_result,
271            int (*digest_stream)(FILE *, void *))
272 {
273   FILE *fp;
274   int err;
275
276   if (STREQ (filename, "-"))
277     {
278       have_read_stdin = 1;
279       fp = stdin;
280 #if O_BINARY
281       /* If we need binary reads from a pipe or redirected stdin, we need
282          to switch it to BINARY mode here, since stdin is already open.  */
283       if (binary)
284         SET_BINARY (fileno (stdin));
285 #endif
286     }
287   else
288     {
289       /* OPENOPTS is a macro.  It varies with the system.
290          Some systems distinguish between internal and
291          external text representations.  */
292
293       fp = fopen (filename, OPENOPTS (binary));
294       if (fp == NULL)
295         {
296           error (0, errno, "%s", filename);
297           return 1;
298         }
299     }
300
301   err = (*digest_stream) (fp, bin_result);
302   if (err)
303     {
304       error (0, errno, "%s", filename);
305       if (fp != stdin)
306         fclose (fp);
307       return 1;
308     }
309
310   if (fp != stdin && fclose (fp) == EOF)
311     {
312       error (0, errno, "%s", filename);
313       return 1;
314     }
315
316   return 0;
317 }
318
319 static int
320 digest_check (const char *checkfile_name, int (*digest_stream)(FILE *, void *))
321 {
322   FILE *checkfile_stream;
323   int n_properly_formated_lines = 0;
324   int n_mismatched_checksums = 0;
325   int n_open_or_read_failures = 0;
326   unsigned char bin_buffer[MAX_DIGEST_BIN_BYTES];
327   size_t line_number;
328   char *line;
329   size_t line_chars_allocated;
330
331   if (STREQ (checkfile_name, "-"))
332     {
333       have_read_stdin = 1;
334       checkfile_name = _("standard input");
335       checkfile_stream = stdin;
336     }
337   else
338     {
339       checkfile_stream = fopen (checkfile_name, "r");
340       if (checkfile_stream == NULL)
341         {
342           error (0, errno, "%s", checkfile_name);
343           return 1;
344         }
345     }
346
347   SET_MODE (fileno (checkfile_stream), O_TEXT);
348   line_number = 0;
349   line = NULL;
350   line_chars_allocated = 0;
351   do
352     {
353       char *filename;
354       int binary;
355       unsigned char *hex_digest;
356       int err;
357       int line_length;
358
359       ++line_number;
360
361       line_length = getline (&line, &line_chars_allocated, checkfile_stream);
362       if (line_length <= 0)
363         break;
364
365       /* Ignore comment lines, which begin with a '#' character.  */
366       if (line[0] == '#')
367         continue;
368
369       /* Remove any trailing newline.  */
370       if (line[line_length - 1] == '\n')
371         line[--line_length] = '\0';
372
373       err = split_3 (line, line_length, &hex_digest, &binary, &filename);
374       if (err || !hex_digits (hex_digest))
375         {
376           if (warn)
377             {
378               error (0, 0,
379                      _("%s: %lu: improperly formatted %s checksum line"),
380                      checkfile_name, (unsigned long) line_number,
381                      DIGEST_TYPE_STRING (algorithm));
382             }
383         }
384       else
385         {
386           static const char bin2hex[] = { '0', '1', '2', '3',
387                                           '4', '5', '6', '7',
388                                           '8', '9', 'a', 'b',
389                                           'c', 'd', 'e', 'f' };
390           int fail;
391
392           ++n_properly_formated_lines;
393
394           fail = digest_file (filename, binary, bin_buffer, digest_stream);
395
396           if (fail)
397             {
398               ++n_open_or_read_failures;
399               if (!status_only)
400                 {
401                   printf (_("%s: FAILED open or read\n"), filename);
402                   fflush (stdout);
403                 }
404             }
405           else
406             {
407               size_t digest_bin_bytes = digest_hex_bytes / 2;
408               size_t cnt;
409               /* Compare generated binary number with text representation
410                  in check file.  Ignore case of hex digits.  */
411               for (cnt = 0; cnt < digest_bin_bytes; ++cnt)
412                 {
413                   if (TOLOWER (hex_digest[2 * cnt]) != bin2hex[bin_buffer[cnt] >> 4]
414                       || (TOLOWER (hex_digest[2 * cnt + 1])
415                           != (bin2hex[bin_buffer[cnt] & 0xf])))
416                     break;
417                 }
418               if (cnt != digest_bin_bytes)
419                 ++n_mismatched_checksums;
420
421               if (!status_only)
422                 {
423                   printf ("%s: %s\n", filename,
424                           (cnt != digest_bin_bytes ? _("FAILED") : _("OK")));
425                   fflush (stdout);
426                 }
427             }
428         }
429     }
430   while (!feof (checkfile_stream) && !ferror (checkfile_stream));
431
432   if (line)
433     free (line);
434
435   if (ferror (checkfile_stream))
436     {
437       error (0, 0, _("%s: read error"), checkfile_name);
438       return 1;
439     }
440
441   if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
442     {
443       error (0, errno, "%s", checkfile_name);
444       return 1;
445     }
446
447   if (n_properly_formated_lines == 0)
448     {
449       /* Warn if no tests are found.  */
450       error (0, 0, _("%s: no properly formatted %s checksum lines found"),
451              checkfile_name, DIGEST_TYPE_STRING (algorithm));
452     }
453   else
454     {
455       if (!status_only)
456         {
457           int n_computed_checkums = (n_properly_formated_lines
458                                      - n_open_or_read_failures);
459
460           if (n_open_or_read_failures > 0)
461             {
462               error (0, 0,
463                      _("WARNING: %d of %d listed %s could not be read"),
464                      n_open_or_read_failures, n_properly_formated_lines,
465                      (n_properly_formated_lines == 1
466                       ? _("file") : _("files")));
467             }
468
469           if (n_mismatched_checksums > 0)
470             {
471               error (0, 0,
472                    _("WARNING: %d of %d computed %s did NOT match"),
473                      n_mismatched_checksums, n_computed_checkums,
474                      (n_computed_checkums == 1
475                       ? _("checksum") : _("checksums")));
476             }
477         }
478     }
479
480   return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
481            && n_open_or_read_failures == 0) ? 0 : 1);
482 }
483
484 int
485 main (int argc, char **argv)
486 {
487   unsigned char bin_buffer[MAX_DIGEST_BIN_BYTES];
488   int do_check = 0;
489   int opt;
490   char **string = NULL;
491   size_t n_strings = 0;
492   size_t err = 0;
493   int file_type_specified = 0;
494
495 #if O_BINARY
496   /* Binary is default on MSDOS, so the actual file contents
497      are used in computation.  */
498   int binary = 1;
499 #else
500   /* Text is default of the Plumb/Lankester format.  */
501   int binary = 0;
502 #endif
503
504   /* Setting values of global variables.  */
505   program_name = argv[0];
506   setlocale (LC_ALL, "");
507   bindtextdomain (PACKAGE, LOCALEDIR);
508   textdomain (PACKAGE);
509
510   atexit (close_stdout);
511
512   while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
513     switch (opt)
514       {
515       case 0:                   /* long option */
516         break;
517       case 1: /* --string */
518         {
519           if (string == NULL)
520             string = (char **) xmalloc ((argc - 1) * sizeof (char *));
521
522           if (optarg == NULL)
523             optarg = "";
524           string[n_strings++] = optarg;
525         }
526         break;
527       case 'b':
528         file_type_specified = 1;
529         binary = 1;
530         break;
531       case 'c':
532         do_check = 1;
533         break;
534       case 2:
535         status_only = 1;
536         warn = 0;
537         break;
538       case 't':
539         file_type_specified = 1;
540         binary = 0;
541         break;
542       case 'w':
543         status_only = 0;
544         warn = 1;
545         break;
546       case_GETOPT_HELP_CHAR;
547       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
548       default:
549         usage (EXIT_FAILURE);
550       }
551
552   min_digest_line_length = MIN_DIGEST_LINE_LENGTH (algorithm);
553   digest_hex_bytes = DIGEST_HEX_BYTES (algorithm);
554
555   if (file_type_specified && do_check)
556     {
557       error (0, 0, _("the --binary and --text options are meaningless when \
558 verifying checksums"));
559       usage (EXIT_FAILURE);
560     }
561
562   if (n_strings > 0 && do_check)
563     {
564       error (0, 0,
565              _("the --string and --check options are mutually exclusive"));
566       usage (EXIT_FAILURE);
567     }
568
569   if (status_only && !do_check)
570     {
571       error (0, 0,
572        _("the --status option is meaningful only when verifying checksums"));
573       usage (EXIT_FAILURE);
574     }
575
576   if (warn && !do_check)
577     {
578       error (0, 0,
579        _("the --warn option is meaningful only when verifying checksums"));
580       usage (EXIT_FAILURE);
581     }
582
583   if (n_strings > 0)
584     {
585       size_t i;
586
587       if (optind < argc)
588         {
589           error (0, 0, _("no files may be specified when using --string"));
590           usage (EXIT_FAILURE);
591         }
592       for (i = 0; i < n_strings; ++i)
593         {
594           size_t cnt;
595           if (algorithm == ALG_MD5)
596             md5_buffer (string[i], strlen (string[i]), bin_buffer);
597           else
598             sha_buffer (string[i], strlen (string[i]), bin_buffer);
599
600           for (cnt = 0; cnt < (digest_hex_bytes / 2); ++cnt)
601             printf ("%02x", bin_buffer[cnt]);
602
603           printf ("  \"%s\"\n", string[i]);
604         }
605     }
606   else if (do_check)
607     {
608       if (optind + 1 < argc)
609         {
610           error (0, 0,
611                  _("only one argument may be specified when using --check"));
612           usage (EXIT_FAILURE);
613         }
614
615       err = digest_check ((optind == argc) ? "-" : argv[optind],
616                           DIGEST_STREAM (algorithm));
617     }
618   else
619     {
620       if (optind == argc)
621         argv[argc++] = "-";
622
623       for (; optind < argc; ++optind)
624         {
625           int fail;
626           char *file = argv[optind];
627
628           fail = digest_file (file, binary, bin_buffer,
629                               DIGEST_STREAM (algorithm));
630           err |= fail;
631           if (!fail)
632             {
633               size_t i;
634
635               /* Output a leading backslash if the file name contains
636                  a newline or backslash.  */
637               if (strchr (file, '\n') || strchr (file, '\\'))
638                 putchar ('\\');
639
640               for (i = 0; i < (digest_hex_bytes / 2); ++i)
641                 printf ("%02x", bin_buffer[i]);
642
643               putchar (' ');
644               if (binary)
645                 putchar ('*');
646               else
647                 putchar (' ');
648
649               /* Translate each NEWLINE byte to the string, "\\n",
650                  and each backslash to "\\\\".  */
651               for (i = 0; i < strlen (file); ++i)
652                 {
653                   switch (file[i])
654                     {
655                     case '\n':
656                       fputs ("\\n", stdout);
657                       break;
658
659                     case '\\':
660                       fputs ("\\\\", stdout);
661                       break;
662
663                     default:
664                       putchar (file[i]);
665                       break;
666                     }
667                 }
668               putchar ('\n');
669             }
670         }
671     }
672
673   if (have_read_stdin && fclose (stdin) == EOF)
674     error (EXIT_FAILURE, errno, _("standard input"));
675
676   exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
677 }