update bug-reporting address
[platform/upstream/coreutils.git] / src / md5sum.c
1 /* Compute MD5 checksum of files or strings according to the definition
2    of MD5 in RFC 1321 from April 1992.
3    Copyright (C) 95, 96, 1997 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include <getopt.h>
26 #include <stdio.h>
27 #include <sys/types.h>
28
29 #include "long-options.h"
30 #include "md5.h"
31 #include "getline.h"
32 #include "system.h"
33 #include "error.h"
34
35 /* Most systems do not distinguish between external and internal
36    text representations.  */
37 /* FIXME: This begs for an autoconf test.  */
38 #if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
39 # define OPENOPTS(BINARY) "r"
40 #else
41 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
42 # ifdef MSDOS
43 #  define TEXT1TO1 "rb"
44 #  define TEXTCNVT "r"
45 # else
46 #  if defined VMS
47 #   define TEXT1TO1 "rb", "ctx=stm"
48 #   define TEXTCNVT "r", "ctx=stm"
49 #  else
50     /* The following line is intended to evoke an error.
51        Using #error is not portable enough.  */
52     "Cannot determine system type."
53 #  endif
54 # endif
55 #endif
56
57 #if _LIBC || STDC_HEADERS
58 # define TOLOWER(c) tolower (c)
59 #else
60 # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
61 #endif
62
63 /* The minimum length of a valid digest line in a file produced
64    by `md5sum FILE' and read by `md5sum --check'.  This length does
65    not include any newline character at the end of a line.  */
66 #define MIN_DIGEST_LINE_LENGTH (32 /* message digest length */ \
67                                 + 2 /* blank and binary indicator */ \
68                                 + 1 /* minimum filename length */ )
69
70 /* Nonzero if any of the files read were the standard input. */
71 static int have_read_stdin;
72
73 /* With --check, don't generate any output.
74    The exit code indicates success or failure.  */
75 static int status_only = 0;
76
77 /* With --check, print a message to standard error warning about each
78    improperly formatted MD5 checksum line.  */
79 static int warn = 0;
80
81 /* The name this program was run with.  */
82 char *program_name;
83
84 static const struct option long_options[] =
85 {
86   { "binary", no_argument, 0, 'b' },
87   { "check", no_argument, 0, 'c' },
88   { "status", no_argument, 0, 2 },
89   { "string", required_argument, 0, 1 },
90   { "text", no_argument, 0, 't' },
91   { "warn", no_argument, 0, 'w' },
92   { NULL, 0, NULL, 0 }
93 };
94
95 char *xmalloc ();
96
97 static void
98 usage (int status)
99 {
100   if (status != 0)
101     fprintf (stderr, _("Try `%s --help' for more information.\n"),
102              program_name);
103   else
104     {
105       printf (_("\
106 Usage: %s [OPTION] [FILE]...\n\
107   or:  %s [OPTION] --check [FILE]\n\
108 Print or check MD5 checksums.\n\
109 With no FILE, or when FILE is -, read standard input.\n\
110 \n\
111   -b, --binary            read files in binary mode\n\
112   -c, --check             check MD5 sums against given list\n\
113   -t, --text              read files in text mode (default)\n\
114 \n\
115 The following two options are useful only when verifying checksums:\n\
116       --status            don't output anything, status code shows success\n\
117   -w, --warn              warn about improperly formated MD5 checksum lines\n\
118 \n\
119       --help              display this help and exit\n\
120       --version           output version information and exit\n\
121 \n\
122 The sums are computed as described in RFC 1321.  When checking, the input\n\
123 should be a former output of this program.  The default mode is to print\n\
124 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
125 text), and name for each FILE.\n"),
126               program_name, program_name, program_name);
127       puts (_("\nReport bugs to <textutils-bugs@gnu.org>."));
128     }
129
130   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
131 }
132
133 static int
134 split_3 (char *s, size_t s_len, char **u, int *binary, char **w)
135 {
136   size_t i;
137   int filename_has_newline = 0;
138
139 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
140
141   i = 0;
142   while (ISWHITE (s[i]))
143     ++i;
144
145   /* The line must have at least 35 (36 if the first is a backslash)
146      more characters to contain correct message digest information.
147      Ignore this line if it is too short.  */
148   if (!(s_len - i >= MIN_DIGEST_LINE_LENGTH
149         || (s[i] == '\\' && s_len - i >= 1 + MIN_DIGEST_LINE_LENGTH)))
150     return 1;
151
152   if (s[i] == '\\')
153     {
154       ++i;
155       filename_has_newline = 1;
156     }
157   *u = &s[i];
158
159   /* The first field has to be the 32-character hexadecimal
160      representation of the message digest.  If it is not followed
161      immediately by a white space it's an error.  */
162   i += 32;
163   if (!ISWHITE (s[i]))
164     return 1;
165
166   s[i++] = '\0';
167
168   if (s[i] != ' ' && s[i] != '*')
169     return 1;
170   *binary = (s[i++] == '*');
171
172   /* All characters between the type indicator and end of line are
173      significant -- that includes leading and trailing white space.  */
174   *w = &s[i];
175
176   if (filename_has_newline)
177     {
178       /* Translate each `\n' string in the file name to a NEWLINE,
179          and each `\\' string to a backslash.  */
180
181       char *dst = &s[i];
182
183       while (i < s_len)
184         {
185           switch (s[i])
186             {
187             case '\\':
188               if (i == s_len - 1)
189                 {
190                   /* A valid line does not end with a backslash.  */
191                   return 1;
192                 }
193               ++i;
194               switch (s[i++])
195                 {
196                 case 'n':
197                   *dst++ = '\n';
198                   break;
199                 case '\\':
200                   *dst++ = '\\';
201                   break;
202                 default:
203                   /* Only `\' or `n' may follow a backslash.  */
204                   return 1;
205                 }
206               break;
207
208             case '\0':
209               /* The file name may not contain a NUL.  */
210               return 1;
211               break;
212
213             default:
214               *dst++ = s[i++];
215               break;
216             }
217         }
218       *dst = '\0';
219     }
220   return 0;
221 }
222
223 static int
224 hex_digits (const char *s)
225 {
226   while (*s)
227     {
228       if (!ISXDIGIT (*s))
229         return 0;
230       ++s;
231     }
232   return 1;
233 }
234
235 /* An interface to md5_stream.  Operate on FILENAME (it may be "-") and
236    put the result in *MD5_RESULT.  Return non-zero upon failure, zero
237    to indicate success.  */
238
239 static int
240 md5_file (const char *filename, int binary, unsigned char *md5_result)
241 {
242   FILE *fp;
243   int err;
244
245   if (strcmp (filename, "-") == 0)
246     {
247       have_read_stdin = 1;
248       fp = stdin;
249     }
250   else
251     {
252       /* OPENOPTS is a macro.  It varies with the system.
253          Some systems distinguish between internal and
254          external text representations.  */
255
256       fp = fopen (filename, OPENOPTS (binary));
257       if (fp == NULL)
258         {
259           error (0, errno, "%s", filename);
260           return 1;
261         }
262     }
263
264   err = md5_stream (fp, md5_result);
265   if (err)
266     {
267       error (0, errno, "%s", filename);
268       if (fp != stdin)
269         fclose (fp);
270       return 1;
271     }
272
273   if (fp != stdin && fclose (fp) == EOF)
274     {
275       error (0, errno, "%s", filename);
276       return 1;
277     }
278
279   return 0;
280 }
281
282 static int
283 md5_check (const char *checkfile_name)
284 {
285   FILE *checkfile_stream;
286   int n_properly_formated_lines = 0;
287   int n_mismatched_checksums = 0;
288   int n_open_or_read_failures = 0;
289   unsigned char md5buffer[16];
290   size_t line_number;
291   char *line;
292   size_t line_chars_allocated;
293
294   if (strcmp (checkfile_name, "-") == 0)
295     {
296       have_read_stdin = 1;
297       checkfile_name = _("standard input");
298       checkfile_stream = stdin;
299     }
300   else
301     {
302       checkfile_stream = fopen (checkfile_name, "r");
303       if (checkfile_stream == NULL)
304         {
305           error (0, errno, "%s", checkfile_name);
306           return 1;
307         }
308     }
309
310   line_number = 0;
311   line = NULL;
312   line_chars_allocated = 0;
313   do
314     {
315       char *filename;
316       int binary;
317       char *md5num;
318       int err;
319       int line_length;
320
321       ++line_number;
322
323       line_length = getline (&line, &line_chars_allocated, checkfile_stream);
324       if (line_length <= 0)
325         break;
326
327       /* Ignore comment lines, which begin with a '#' character.  */
328       if (line[0] == '#')
329         continue;
330
331       /* Remove any trailing newline.  */
332       if (line[line_length - 1] == '\n')
333         line[--line_length] = '\0';
334
335       err = split_3 (line, line_length, &md5num, &binary, &filename);
336       if (err || !hex_digits (md5num))
337         {
338           if (warn)
339             {
340               error (0, 0,
341                      _("%s: %lu: improperly formatted MD5 checksum line"),
342                      checkfile_name, (unsigned long) line_number);
343             }
344         }
345       else
346         {
347           static const char bin2hex[] = { '0', '1', '2', '3',
348                                           '4', '5', '6', '7',
349                                           '8', '9', 'a', 'b',
350                                           'c', 'd', 'e', 'f' };
351           int fail;
352
353           ++n_properly_formated_lines;
354
355           fail = md5_file (filename, binary, md5buffer);
356
357           if (fail)
358             {
359               ++n_open_or_read_failures;
360               if (!status_only)
361                 {
362                   printf (_("%s: FAILED open or read\n"), filename);
363                   fflush (stdout);
364                 }
365             }
366           else
367             {
368               size_t cnt;
369               /* Compare generated binary number with text representation
370                  in check file.  Ignore case of hex digits.  */
371               for (cnt = 0; cnt < 16; ++cnt)
372                 {
373                   if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
374                       || (TOLOWER (md5num[2 * cnt + 1])
375                           != (bin2hex[md5buffer[cnt] & 0xf])))
376                     break;
377                 }
378               if (cnt != 16)
379                 ++n_mismatched_checksums;
380
381               if (!status_only)
382                 {
383                   printf ("%s: %s\n", filename,
384                           (cnt != 16 ? _("FAILED") : _("OK")));
385                   fflush (stdout);
386                 }
387             }
388         }
389     }
390   while (!feof (checkfile_stream) && !ferror (checkfile_stream));
391
392   if (line)
393     free (line);
394
395   if (ferror (checkfile_stream))
396     {
397       error (0, 0, _("%s: read error"), checkfile_name);
398       return 1;
399     }
400
401   if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
402     {
403       error (0, errno, "%s", checkfile_name);
404       return 1;
405     }
406
407   if (n_properly_formated_lines == 0)
408     {
409       /* Warn if no tests are found.  */
410       error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
411              checkfile_name);
412     }
413   else
414     {
415       if (!status_only)
416         {
417           int n_computed_checkums = (n_properly_formated_lines
418                                      - n_open_or_read_failures);
419
420           if (n_open_or_read_failures > 0)
421             {
422               error (0, 0,
423                    _("WARNING: %d of %d listed %s could not be read\n"),
424                      n_open_or_read_failures, n_properly_formated_lines,
425                      (n_properly_formated_lines == 1
426                       ? _("file") : _("files")));
427             }
428
429           if (n_mismatched_checksums > 0)
430             {
431               error (0, 0,
432                    _("WARNING: %d of %d computed %s did NOT match"),
433                      n_mismatched_checksums, n_computed_checkums,
434                      (n_computed_checkums == 1
435                       ? _("checksum") : _("checksums")));
436             }
437         }
438     }
439
440   return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
441            && n_open_or_read_failures == 0) ? 0 : 1);
442 }
443
444 int
445 main (int argc, char **argv)
446 {
447   unsigned char md5buffer[16];
448   int do_check = 0;
449   int opt;
450   char **string = NULL;
451   size_t n_strings = 0;
452   size_t err = 0;
453   int file_type_specified = 0;
454
455   /* Text is default of the Plumb/Lankester format.  */
456   int binary = 0;
457
458   /* Setting values of global variables.  */
459   program_name = argv[0];
460   setlocale (LC_ALL, "");
461   bindtextdomain (PACKAGE, LOCALEDIR);
462   textdomain (PACKAGE);
463
464   parse_long_options (argc, argv, "md5sum", GNU_PACKAGE, VERSION, usage);
465
466   while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
467     switch (opt)
468       {
469       case 0:                   /* long option */
470         break;
471       case 1: /* --string */
472         {
473           if (string == NULL)
474             string = (char **) xmalloc ((argc - 1) * sizeof (char *));
475
476           if (optarg == NULL)
477             optarg = "";
478           string[n_strings++] = optarg;
479         }
480         break;
481       case 'b':
482         file_type_specified = 1;
483         binary = 1;
484         break;
485       case 'c':
486         do_check = 1;
487         break;
488       case 2:
489         status_only = 1;
490         warn = 0;
491         break;
492       case 't':
493         file_type_specified = 1;
494         binary = 0;
495         break;
496       case 'w':
497         status_only = 0;
498         warn = 1;
499         break;
500       default:
501         usage (EXIT_FAILURE);
502       }
503
504   if (file_type_specified && do_check)
505     {
506       error (0, 0, _("the --binary and --text options are meaningless when \
507 verifying checksums"));
508       usage (EXIT_FAILURE);
509     }
510
511   if (n_strings > 0 && do_check)
512     {
513       error (0, 0,
514              _("the --string and --check options are mutually exclusive"));
515       usage (EXIT_FAILURE);
516     }
517
518   if (status_only && !do_check)
519     {
520       error (0, 0,
521        _("the --status option is meaningful only when verifying checksums"));
522       usage (EXIT_FAILURE);
523     }
524
525   if (warn && !do_check)
526     {
527       error (0, 0,
528        _("the --warn option is meaningful only when verifying checksums"));
529       usage (EXIT_FAILURE);
530     }
531
532   if (n_strings > 0)
533     {
534       size_t i;
535
536       if (optind < argc)
537         {
538           error (0, 0, _("no files may be specified when using --string"));
539           usage (EXIT_FAILURE);
540         }
541       for (i = 0; i < n_strings; ++i)
542         {
543           size_t cnt;
544           md5_buffer (string[i], strlen (string[i]), md5buffer);
545
546           for (cnt = 0; cnt < 16; ++cnt)
547             printf ("%02x", md5buffer[cnt]);
548
549           printf ("  \"%s\"\n", string[i]);
550         }
551     }
552   else if (do_check)
553     {
554       if (optind + 1 < argc)
555         {
556           error (0, 0,
557                  _("only one argument may be specified when using --check"));
558           usage (EXIT_FAILURE);
559         }
560
561       err = md5_check ((optind == argc) ? "-" : argv[optind]);
562     }
563   else
564     {
565       if (optind == argc)
566         argv[argc++] = "-";
567
568       for (; optind < argc; ++optind)
569         {
570           int fail;
571           char *file = argv[optind];
572
573           fail = md5_file (file, binary, md5buffer);
574           err |= fail;
575           if (!fail)
576             {
577               size_t i;
578
579               /* Output a leading backslash if the file name contains
580                  a newline.  */
581               if (strchr (file, '\n'))
582                 putchar ('\\');
583
584               for (i = 0; i < 16; ++i)
585                 printf ("%02x", md5buffer[i]);
586
587               putchar (' ');
588               if (binary)
589                 putchar ('*');
590               else
591                 putchar (' ');
592
593               /* Translate each NEWLINE byte to the string, "\\n",
594                  and each backslash to "\\\\".  */
595               for (i = 0; i < strlen (file); ++i)
596                 {
597                   switch (file[i])
598                     {
599                     case '\n':
600                       fputs ("\\n", stdout);
601                       break;
602
603                     case '\\':
604                       fputs ("\\\\", stdout);
605                       break;
606
607                     default:
608                       putchar (file[i]);
609                       break;
610                     }
611                 }
612               putchar ('\n');
613             }
614         }
615     }
616
617   if (fclose (stdout) == EOF)
618     error (EXIT_FAILURE, errno, _("write error"));
619
620   if (have_read_stdin && fclose (stdin) == EOF)
621     error (EXIT_FAILURE, errno, _("standard input"));
622
623   exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
624 }