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