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