.
[coreutils.git] / src / md5sum.c
blob2e2759d0f66a816afbf6357aa382e02e9e6f798a
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 Free Software Foundation, Inc.
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.
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.
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. */
19 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>. */
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <getopt.h>
26 #include <stdio.h>
27 #include <sys/types.h>
29 #include "long-options.h"
30 #include "md5.h"
31 #include "getline.h"
32 #include "system.h"
33 #include "error.h"
34 #include "version.h"
36 /* Most systems do not distinguish between external and internal
37 text representations. */
38 #if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION
39 # define OPENOPTS(BINARY) "r"
40 #else
41 # ifdef MSDOS
42 # define TEXT1TO1 "rb"
43 # define TEXTCNVT "r"
44 # else
45 # if defined VMS
46 # define TEXT1TO1 "rb", "ctx=stm"
47 # define TEXTCNVT "r", "ctx=stm"
48 # else
49 /* The following line is intended to evoke an error.
50 Using #error is not portable enough. */
51 "Cannot determine system type."
52 # endif
53 # endif
54 # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)
55 #endif
57 #if _LIBC || STDC_HEADERS
58 # define TOLOWER(c) tolower (c)
59 #else
60 # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
61 #endif
63 /* Nonzero if any of the files read were the standard input. */
64 static int have_read_stdin;
66 /* With --check, don't generate any output.
67 The exit code indicates success or failure. */
68 static int status_only = 0;
70 /* With --check, print a message to standard error warning about each
71 improperly formatted MD5 checksum line. */
72 static int warn = 0;
74 /* The name this program was run with. */
75 char *program_name;
77 static const struct option long_options[] =
79 { "binary", no_argument, 0, 'b' },
80 { "check", no_argument, 0, 'c' },
81 { "status", no_argument, 0, 2 },
82 { "string", required_argument, 0, 1 },
83 { "text", no_argument, 0, 't' },
84 { "warn", no_argument, 0, 'w' },
85 { NULL, 0, NULL, 0 }
88 char *xmalloc ();
90 static void
91 usage (int status)
93 if (status != 0)
94 fprintf (stderr, _("Try `%s --help' for more information.\n"),
95 program_name);
96 else
97 printf (_("\
98 Usage: %s [OPTION] [FILE]...\n\
99 or: %s [OPTION] --check [FILE]\n\
100 or: %s [OPTION] --string=STRING ...\n\
101 Print or check MD5 checksums.\n\
102 With no FILE, or when FILE is -, read standard input.\n\
104 -b, --binary read files in binary mode\n\
105 -t, --text read files in text mode (default)\n\
106 -c, --check check MD5 sums against given list\n\
108 The following two options are useful only when verifying checksums:\n\
109 --status don't output anything, status code shows success\n\
110 -w, --warn warn about improperly formated MD5 checksum lines\n\
112 --string=STRING compute checksum for STRING\n\
113 --help display this help and exit\n\
114 --version output version information and exit\n\
116 The sums are computed as described in RFC 1321. When checking, the input\n\
117 should be a former output of this program. The default mode is to print\n\
118 a line with checksum, a character indicating type (`*' for binary, ` ' for\n\
119 text), and name for each FILE.\n"),
120 program_name, program_name, program_name);
122 exit (status);
125 /* FIXME: this format loses with filenames containing newline. */
127 static int
128 split_3 (char *s, char **u, int *binary, char **w)
130 size_t i;
132 #define ISWHITE(c) ((c) == ' ' || (c) == '\t')
134 i = 0;
135 while (ISWHITE (s[i]))
136 ++i;
138 /* The line has to be at least 35 characters long to contain correct
139 message digest information. */
140 if (strlen (&s[i]) >= 35)
142 *u = &s[i];
144 /* The first field has to be the 32-character hexadecimal
145 representation of the message digest. If it not immediately
146 followed by a white space it's an error. */
147 i += 32;
148 if (!ISWHITE (s[i]))
149 return 1;
151 s[i++] = '\0';
153 if (s[i] != ' ' && s[i] != '*')
154 return 1;
155 *binary = s[i++] == '*';
157 /* All characters between the type indicator and end of line are
158 significant -- that includes leading and trailing white space. */
159 *w = &s[i];
161 /* So this line is valid as long as there is at least one character
162 for the filename. */
163 return (**w ? 0 : 1);
165 return 1;
168 static int
169 hex_digits (const char *s)
171 while (*s)
173 if (!ISXDIGIT (*s))
174 return 0;
175 ++s;
177 return 1;
180 /* FIXME: allow newline in filename by encoding it. */
182 static int
183 md5_file (const char *filename, int binary, unsigned char *md5_result)
185 FILE *fp;
186 int err;
188 if (strcmp (filename, "-") == 0)
190 have_read_stdin = 1;
191 fp = stdin;
193 else
195 /* OPENOPTS is a macro. It varies with the system.
196 Some systems distinguish between internal and
197 external text representations. */
199 fp = fopen (filename, OPENOPTS (binary));
200 if (fp == NULL)
202 error (0, errno, "%s", filename);
203 return 1;
207 err = md5_stream (fp, md5_result);
208 if (err)
210 error (0, errno, "%s", filename);
211 if (fp != stdin)
212 fclose (fp);
213 return 1;
216 if (fp != stdin && fclose (fp) == EOF)
218 error (0, errno, "%s", filename);
219 return 1;
222 return 0;
225 static int
226 md5_check (const char *checkfile_name, int binary)
228 FILE *checkfile_stream;
229 int n_properly_formated_lines = 0;
230 int n_mismatched_checksums = 0;
231 int n_open_or_read_failures = 0;
232 unsigned char md5buffer[16];
233 size_t line_number;
234 char *line;
235 size_t line_chars_allocated;
237 if (strcmp (checkfile_name, "-") == 0)
239 have_read_stdin = 1;
240 checkfile_name = _("standard input");
241 checkfile_stream = stdin;
243 else
245 checkfile_stream = fopen (checkfile_name, "r");
246 if (checkfile_stream == NULL)
248 error (0, errno, "%s", checkfile_name);
249 return 1;
253 line_number = 0;
254 line = NULL;
255 line_chars_allocated = 0;
258 char *filename;
259 int type_flag;
260 char *md5num;
261 int err;
262 int line_length;
264 ++line_number;
266 line_length = getline (&line, &line_chars_allocated, checkfile_stream);
267 if (line_length <= 0)
268 break;
270 /* Ignore comment lines, which begin with a '#' character. */
271 if (line[0] == '#')
272 continue;
274 /* Remove any trailing newline. */
275 if (line[line_length - 1] == '\n')
276 line[--line_length] = '\0';
278 err = split_3 (line, &md5num, &type_flag, &filename);
279 if (err || !hex_digits (md5num))
281 if (warn)
283 error (0, 0,
284 _("%s: %lu: improperly formatted MD5 checksum line"),
285 checkfile_name, (unsigned long) line_number);
288 else
290 static const char bin2hex[] = { '0', '1', '2', '3',
291 '4', '5', '6', '7',
292 '8', '9', 'a', 'b',
293 'c', 'd', 'e', 'f' };
294 int fail;
296 ++n_properly_formated_lines;
298 fail = md5_file (filename, binary, md5buffer);
300 if (fail)
302 ++n_open_or_read_failures;
303 if (!status_only)
305 printf (_("%s: FAILED open or read\n"), filename);
306 fflush (stdout);
309 else
311 size_t cnt;
312 /* Compare generated binary number with text representation
313 in check file. Ignore case of hex digits. */
314 for (cnt = 0; cnt < 16; ++cnt)
316 if (TOLOWER (md5num[2 * cnt]) != bin2hex[md5buffer[cnt] >> 4]
317 || (TOLOWER (md5num[2 * cnt + 1])
318 != (bin2hex[md5buffer[cnt] & 0xf])))
319 break;
321 if (cnt != 16)
322 ++n_mismatched_checksums;
324 if (!status_only)
326 printf ("%s: %s\n", filename,
327 (cnt != 16 ? _("FAILED") : _("OK")));
328 fflush (stdout);
333 while (!feof (checkfile_stream) && !ferror (checkfile_stream));
335 if (line)
336 free (line);
338 if (ferror (checkfile_stream))
340 error (0, 0, _("%s: read error"), checkfile_name);
341 return 1;
344 if (checkfile_stream != stdin && fclose (checkfile_stream) == EOF)
346 error (0, errno, "%s", checkfile_name);
347 return 1;
350 if (n_properly_formated_lines == 0)
352 /* Warn if no tests are found. */
353 error (0, 0, _("%s: no properly formatted MD5 checksum lines found"),
354 checkfile_name);
356 else
358 if (!status_only)
360 int n_computed_checkums = (n_properly_formated_lines
361 - n_open_or_read_failures);
363 if (n_open_or_read_failures > 0)
365 error (0, 0,
366 _("WARNING: %d of %d listed file%s could not be read\n"),
367 n_open_or_read_failures, n_properly_formated_lines,
368 (n_properly_formated_lines == 1 ? "" : "s"));
371 if (n_mismatched_checksums > 0)
373 error (0, 0,
374 _("WARNING: %d of %d computed checksum%s did NOT match\n"),
375 n_mismatched_checksums, n_computed_checkums,
376 (n_computed_checkums == 1 ? "" : "s"));
381 return ((n_properly_formated_lines > 0 && n_mismatched_checksums == 0
382 && n_open_or_read_failures == 0) ? 0 : 1);
386 main (int argc, char **argv)
388 unsigned char md5buffer[16];
389 int do_check = 0;
390 int do_version = 0;
391 int opt;
392 char **string = NULL;
393 size_t n_strings = 0;
394 size_t i;
395 size_t err = 0;
397 /* Text is default of the Plumb/Lankester format. */
398 int binary = 0;
400 /* Setting values of global variables. */
401 program_name = argv[0];
402 setlocale (LC_ALL, "");
403 bindtextdomain (PACKAGE, LOCALEDIR);
404 textdomain (PACKAGE);
406 parse_long_options (argc, argv, "md5sum", version_string, usage);
408 while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL))
409 != EOF)
410 switch (opt)
412 case 0: /* long option */
413 break;
414 case 1: /* --string */
416 if (string == NULL)
417 string = (char **) xmalloc ((argc - 1) * sizeof (char *));
419 if (optarg == NULL)
420 optarg = "";
421 string[n_strings++] = optarg;
423 break;
424 case 'b':
425 binary = 1;
426 break;
427 case 'c':
428 do_check = 1;
429 break;
430 case 2:
431 status_only = 1;
432 warn = 0;
433 break;
434 case 't':
435 binary = 0;
436 break;
437 case 'w':
438 status_only = 0;
439 warn = 1;
440 break;
441 default:
442 usage (EXIT_FAILURE);
445 if (do_version)
447 printf ("md5sum - %s\n", version_string);
448 exit (EXIT_SUCCESS);
451 if (n_strings > 0 && do_check)
453 error (0, 0,
454 _("the --string and --check options are mutually exclusive"));
455 usage (EXIT_FAILURE);
458 if (status_only && !do_check)
460 error (0, 0,
461 _("the --status option is meaningful only when verifying checksums"));
462 usage (EXIT_FAILURE);
465 if (warn && !do_check)
467 error (0, 0,
468 _("the --warn option is meaningful only when verifying checksums"));
469 usage (EXIT_FAILURE);
472 if (n_strings > 0)
474 if (optind < argc)
476 error (0, 0, _("no files may be specified when using --string"));
477 usage (EXIT_FAILURE);
479 for (i = 0; i < n_strings; ++i)
481 size_t cnt;
482 md5_buffer (string[i], strlen (string[i]), md5buffer);
484 for (cnt = 0; cnt < 16; ++cnt)
485 printf ("%02x", md5buffer[cnt]);
487 printf (" \"%s\"\n", string[i]);
490 else if (do_check)
492 if (optind + 1 < argc)
494 error (0, 0,
495 _("only one argument may be specified when using --check"));
496 usage (EXIT_FAILURE);
499 err = md5_check ((optind == argc) ? "-" : argv[optind], binary);
501 else
503 if (optind == argc)
504 argv[argc++] = "-";
506 for (; optind < argc; ++optind)
508 size_t i;
509 int fail;
511 fail = md5_file (argv[optind], binary, md5buffer);
512 err |= fail;
513 if (!fail)
515 for (i = 0; i < 16; ++i)
516 printf ("%02x", md5buffer[i]);
518 printf (" %c%s\n", binary ? '*' : ' ', argv[optind]);
523 if (fclose (stdout) == EOF)
524 error (EXIT_FAILURE, errno, _("write error"));
526 if (have_read_stdin && fclose (stdin) == EOF)
527 error (EXIT_FAILURE, errno, _("standard input"));
529 exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);