home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / md5sum.c < prev    next >
C/C++ Source or Header  |  1998-04-11  |  15KB  |  631 lines

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