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