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