(split_3): Rename local variable, to `escaped_filename'.
[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, 1998 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 static void
96 usage (int status)
97 {
98   if (status != 0)
99     fprintf (stderr, _("Try `%s --help' for more information.\n"),
100              program_name);
101   else
102     {
103       printf (_("\
104 Usage: %s [OPTION] [FILE]...\n\
105   or:  %s [OPTION] --check [FILE]\n\
106 Print or check MD5 checksums.\n\
107 With no FILE, or when FILE is -, read standard input.\n\
108 \n\
109   -b, --binary            read files in binary mode\n\
110   -c, --check             check MD5 sums against given list\n\
111   -t, --text              read files in text mode (default)\n\
112 \n\
113 The following two options are useful only when verifying checksums:\n\
114       --status            don't output anything, status code shows success\n\
115   -w, --warn              warn about improperly formated MD5 checksum lines\n\
116 \n\
117       --help              display this help and exit\n\
118       --version           output version information and exit\n\
119 \n\
120 The sums are computed as described in RFC 1321.  When checking, the input\n\
121 should be a former output of this program.  The default mode is to print\n\
122 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
123 text), and name for each FILE.\n"),
124               program_name, program_name, program_name);
125       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
126     }
127
128   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
129 }
130
131 static int
132 split_3 (char *s, size_t s_len, unsigned char **u, int *binary, char **w)
133 {
134   size_t i;
135   int escaped_filename = 0;
136
137 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
138
139   i = 0;
140   while (ISWHITE (s[i]))
141     ++i;
142
143   /* The line must have at least 35 (36 if the first is a backslash)
144      more characters to contain correct message digest information.
145      Ignore this line if it is too short.  */
146   if (!(s_len - i >= MIN_DIGEST_LINE_LENGTH
147         || (s[i] == '\\' && s_len - i >= 1 + MIN_DIGEST_LINE_LENGTH)))
148     return 1;
149
150   if (s[i] == '\\')
151     {
152       ++i;
153       escaped_filename = 1;
154     }
155   *u = (unsigned char *) &s[i];
156
157   /* The first field has to be the 32-character hexadecimal
158      representation of the message digest.  If it is not followed
159      immediately by a white space it's an error.  */
160   i += 32;
161   if (!ISWHITE (s[i]))
162     return 1;
163
164   s[i++] = '\0';
165
166   if (s[i] != ' ' && s[i] != '*')
167     return 1;
168   *binary = (s[i++] == '*');
169
170   /* All characters between the type indicator and end of line are
171      significant -- that includes leading and trailing white space.  */
172   *w = &s[i];
173
174   if (escaped_filename)
175     {
176       /* Translate each `\n' string in the file name to a NEWLINE,
177          and each `\\' string to a backslash.  */
178
179       char *dst = &s[i];
180
181       while (i < s_len)
182         {
183           switch (s[i])
184             {
185             case '\\':
186               if (i == s_len - 1)
187                 {
188                   /* A valid line does not end with a backslash.  */
189                   return 1;
190                 }
191               ++i;
192               switch (s[i++])
193                 {
194                 case 'n':
195                   *dst++ = '\n';
196                   break;
197                 case '\\':
198                   *dst++ = '\\';
199                   break;
200                 default:
201                   /* Only `\' or `n' may follow a backslash.  */
202                   return 1;
203                 }
204               break;
205
206             case '\0':
207               /* The file name may not contain a NUL.  */
208               return 1;
209               break;
210
211             default:
212               *dst++ = s[i++];
213               break;
214             }
215         }
216       *dst = '\0';
217     }
218   return 0;
219 }
220
221 static int
222 hex_digits (unsigned char const *s)
223 {
224   while (*s)
225     {
226       if (!ISXDIGIT (*s))
227         return 0;
228       ++s;
229     }
230   return 1;
231 }
232
233 /* An interface to md5_stream.  Operate on FILENAME (it may be "-") and
234    put the result in *MD5_RESULT.  Return non-zero upon failure, zero
235    to indicate success.  */
236
237 static int
238 md5_file (const char *filename, int binary, unsigned char *md5_result)
239 {
240   FILE *fp;
241   int err;
242
243   if (STREQ (filename, "-"))
244     {
245       have_read_stdin = 1;
246       fp = stdin;
247     }
248   else
249     {
250       /* OPENOPTS is a macro.  It varies with the system.
251          Some systems distinguish between internal and
252          external text representations.  */
253
254       fp = fopen (filename, OPENOPTS (binary));
255       if (fp == NULL)
256         {
257           error (0, errno, "%s", filename);
258           return 1;
259         }
260     }
261
262   err = md5_stream (fp, md5_result);
263   if (err)
264     {
265       error (0, errno, "%s", filename);
266       if (fp != stdin)
267         fclose (fp);
268       return 1;
269     }
270
271   if (fp != stdin && fclose (fp) == EOF)
272     {
273       error (0, errno, "%s", filename);
274       return 1;
275     }
276
277   return 0;
278 }
279
280 static int
281 md5_check (const char *checkfile_name)
282 {
283   FILE *checkfile_stream;
284   int n_properly_formated_lines = 0;
285   int n_mismatched_checksums = 0;
286   int n_open_or_read_failures = 0;
287   unsigned char md5buffer[16];
288   size_t line_number;
289   char *line;
290   size_t line_chars_allocated;
291
292   if (STREQ (checkfile_name, "-"))
293     {
294       have_read_stdin = 1;
295       checkfile_name = _("standard input");
296       checkfile_stream = stdin;
297     }
298   else
299     {
300       checkfile_stream = fopen (checkfile_name, "r");
301       if (checkfile_stream == NULL)
302         {
303           error (0, errno, "%s", checkfile_name);
304           return 1;
305         }
306     }
307
308   line_number = 0;
309   line = NULL;
310   line_chars_allocated = 0;
311   do
312     {
313       char *filename;
314       int binary;
315       unsigned char *md5num;
316       int err;
317       int line_length;
318
319       ++line_number;
320
321       line_length = getline (&line, &line_chars_allocated, checkfile_stream);
322       if (line_length <= 0)
323         break;
324
325       /* Ignore comment lines, which begin with a '#' character.  */
326       if (line[0] == '#')
327         continue;
328
329       /* Remove any trailing newline.  */
330       if (line[line_length - 1] == '\n')
331         line[--line_length] = '\0';
332
333       err = split_3 (line, line_length, &md5num, &binary, &filename);
334       if (err || !hex_digits (md5num))
335         {
336           if (warn)
337             {
338               error (0, 0,
339                      _("%s: %lu: improperly formatted MD5 checksum line"),
340                      checkfile_name, (unsigned long) line_number);
341             }
342         }
343       else
344         {
345           static const char bin2hex[] = { '0', '1', '2', '3',
346                                           '4', '5', '6', '7',
347                                           '8', '9', 'a', 'b',
348                                           'c', 'd', 'e', 'f' };
349           int fail;
350
351           ++n_properly_formated_lines;
352
353           fail = md5_file (filename, binary, md5buffer);
354
355           if (fail)
356             {
357               ++n_open_or_read_failures;
358               if (!status_only)
359                 {
360                   printf (_("%s: FAILED open or read\n"), filename);
361                   fflush (stdout);
362                 }
363             }
364           else
365             {
366               size_t cnt;
367               /* Compare generated binary number with text representation
368                  in check file.  Ignore case of hex digits.  */
369               for (cnt = 0; cnt < 16; ++cnt)
370                 {
371                   if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
372                       || (TOLOWER (md5num[2 * cnt + 1])
373                           != (bin2hex[md5buffer[cnt] & 0xf])))
374                     break;
375                 }
376               if (cnt != 16)
377                 ++n_mismatched_checksums;
378
379               if (!status_only)
380                 {
381                   printf ("%s: %s\n", filename,
382                           (cnt != 16 ? _("FAILED") : _("OK")));
383                   fflush (stdout);
384                 }
385             }
386         }
387     }
388   while (!feof (checkfile_stream) && !ferror (checkfile_stream));
389
390   if (line)
391     free (line);
392
393   if (ferror (checkfile_stream))
394     {
395       error (0, 0, _("%s: read error"), checkfile_name);
396       return 1;
397     }
398
399   if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
400     {
401       error (0, errno, "%s", checkfile_name);
402       return 1;
403     }
404
405   if (n_properly_formated_lines == 0)
406     {
407       /* Warn if no tests are found.  */
408       error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
409              checkfile_name);
410     }
411   else
412     {
413       if (!status_only)
414         {
415           int n_computed_checkums = (n_properly_formated_lines
416                                      - n_open_or_read_failures);
417
418           if (n_open_or_read_failures > 0)
419             {
420               error (0, 0,
421                    _("WARNING: %d of %d listed %s could not be read\n"),
422                      n_open_or_read_failures, n_properly_formated_lines,
423                      (n_properly_formated_lines == 1
424                       ? _("file") : _("files")));
425             }
426
427           if (n_mismatched_checksums > 0)
428             {
429               error (0, 0,
430                    _("WARNING: %d of %d computed %s did NOT match"),
431                      n_mismatched_checksums, n_computed_checkums,
432                      (n_computed_checkums == 1
433                       ? _("checksum") : _("checksums")));
434             }
435         }
436     }
437
438   return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
439            && n_open_or_read_failures == 0) ? 0 : 1);
440 }
441
442 int
443 main (int argc, char **argv)
444 {
445   unsigned char md5buffer[16];
446   int do_check = 0;
447   int opt;
448   char **string = NULL;
449   size_t n_strings = 0;
450   size_t err = 0;
451   int file_type_specified = 0;
452
453   /* Text is default of the Plumb/Lankester format.  */
454   int binary = 0;
455
456   /* Setting values of global variables.  */
457   program_name = argv[0];
458   setlocale (LC_ALL, "");
459   bindtextdomain (PACKAGE, LOCALEDIR);
460   textdomain (PACKAGE);
461
462   parse_long_options (argc, argv, "md5sum", GNU_PACKAGE, VERSION, usage);
463
464   while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
465     switch (opt)
466       {
467       case 0:                   /* long option */
468         break;
469       case 1: /* --string */
470         {
471           if (string == NULL)
472             string = (char **) xmalloc ((argc - 1) * sizeof (char *));
473
474           if (optarg == NULL)
475             optarg = "";
476           string[n_strings++] = optarg;
477         }
478         break;
479       case 'b':
480         file_type_specified = 1;
481         binary = 1;
482         break;
483       case 'c':
484         do_check = 1;
485         break;
486       case 2:
487         status_only = 1;
488         warn = 0;
489         break;
490       case 't':
491         file_type_specified = 1;
492         binary = 0;
493         break;
494       case 'w':
495         status_only = 0;
496         warn = 1;
497         break;
498       default:
499         usage (EXIT_FAILURE);
500       }
501
502   if (file_type_specified && do_check)
503     {
504       error (0, 0, _("the --binary and --text options are meaningless when \
505 verifying checksums"));
506       usage (EXIT_FAILURE);
507     }
508
509   if (n_strings > 0 && do_check)
510     {
511       error (0, 0,
512              _("the --string and --check options are mutually exclusive"));
513       usage (EXIT_FAILURE);
514     }
515
516   if (status_only && !do_check)
517     {
518       error (0, 0,
519        _("the --status option is meaningful only when verifying checksums"));
520       usage (EXIT_FAILURE);
521     }
522
523   if (warn && !do_check)
524     {
525       error (0, 0,
526        _("the --warn option is meaningful only when verifying checksums"));
527       usage (EXIT_FAILURE);
528     }
529
530   if (n_strings > 0)
531     {
532       size_t i;
533
534       if (optind < argc)
535         {
536           error (0, 0, _("no files may be specified when using --string"));
537           usage (EXIT_FAILURE);
538         }
539       for (i = 0; i < n_strings; ++i)
540         {
541           size_t cnt;
542           md5_buffer (string[i], strlen (string[i]), md5buffer);
543
544           for (cnt = 0; cnt < 16; ++cnt)
545             printf ("%02x", md5buffer[cnt]);
546
547           printf ("  \"%s\"\n", string[i]);
548         }
549     }
550   else if (do_check)
551     {
552       if (optind + 1 < argc)
553         {
554           error (0, 0,
555                  _("only one argument may be specified when using --check"));
556           usage (EXIT_FAILURE);
557         }
558
559       err = md5_check ((optind == argc) ? "-" : argv[optind]);
560     }
561   else
562     {
563       if (optind == argc)
564         argv[argc++] = "-";
565
566       for (; optind < argc; ++optind)
567         {
568           int fail;
569           char *file = argv[optind];
570
571           fail = md5_file (file, binary, md5buffer);
572           err |= fail;
573           if (!fail)
574             {
575               size_t i;
576
577               /* Output a leading backslash if the file name contains
578                  a newline or backslash.  */
579               if (strchr (file, '\n') || strchr (file, '\\'))
580                 putchar ('\\');
581
582               for (i = 0; i < 16; ++i)
583                 printf ("%02x", md5buffer[i]);
584
585               putchar (' ');
586               if (binary)
587                 putchar ('*');
588               else
589                 putchar (' ');
590
591               /* Translate each NEWLINE byte to the string, "\\n",
592                  and each backslash to "\\\\".  */
593               for (i = 0; i < strlen (file); ++i)
594                 {
595                   switch (file[i])
596                     {
597                     case '\n':
598                       fputs ("\\n", stdout);
599                       break;
600
601                     case '\\':
602                       fputs ("\\\\", stdout);
603                       break;
604
605                     default:
606                       putchar (file[i]);
607                       break;
608                     }
609                 }
610               putchar ('\n');
611             }
612         }
613     }
614
615   if (fclose (stdout) == EOF)
616     error (EXIT_FAILURE, errno, _("write error"));
617
618   if (have_read_stdin && fclose (stdin) == EOF)
619     error (EXIT_FAILURE, errno, _("standard input"));
620
621   exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
622 }