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