Back to home page

LXR

 
 

    


File indexing completed on 2025-05-11 08:24:19

0001 /*
0002  *  MD5 Shell Command Implmentation
0003  *
0004  *  The license and distribution terms for this file may be
0005  *  found in the file LICENSE in this distribution or at
0006  *  http://www.rtems.org/license/LICENSE.
0007  */
0008 
0009 #ifdef HAVE_CONFIG_H
0010 #include "config.h"
0011 #endif
0012 
0013 #include <errno.h>
0014 #include <fcntl.h>
0015 #include <stdio.h>
0016 #include <stdlib.h>
0017 #include <string.h>
0018 #include <sys/types.h>
0019 #include <unistd.h>
0020 
0021 #include <rtems.h>
0022 #include <rtems/shell.h>
0023 
0024 #include <md5.h>
0025 
0026 #define BUFFER_SIZE (4 * 1024)
0027 
0028 static int rtems_shell_main_md5(
0029   int   argc,
0030   char *argv[])
0031 {
0032   uint8_t* buffer;
0033   uint8_t  hash[16];
0034   size_t   h;
0035 
0036   buffer = malloc(BUFFER_SIZE);
0037   if (!buffer)
0038   {
0039     printf("error: no memory\n");
0040     return 1;
0041   }
0042 
0043   --argc;
0044   ++argv;
0045 
0046   while (argc)
0047   {
0048     struct stat sb;
0049     MD5_CTX     md5;
0050     int         in;
0051 
0052     if (stat(*argv, &sb) < 0)
0053     {
0054         free(buffer);
0055         printf("error: stat of %s: %s\n", *argv, strerror(errno));
0056         return 1;
0057     }
0058 
0059     in = open(*argv, O_RDONLY);
0060     if (in < 0)
0061     {
0062         free(buffer);
0063         printf("error: opening %s: %s\n", *argv, strerror(errno));
0064         return 1;
0065     }
0066 
0067     MD5Init(&md5);
0068 
0069     while (sb.st_size)
0070     {
0071       ssize_t size = sb.st_size > BUFFER_SIZE ? BUFFER_SIZE : sb.st_size;
0072 
0073       if (read(in, buffer, size) != size)
0074       {
0075         close(in);
0076         free(buffer);
0077         printf("error: reading %s: %s\n", *argv, strerror(errno));
0078         return 1;
0079       }
0080 
0081       MD5Update(&md5, buffer, size);
0082 
0083       sb.st_size -= size;
0084     }
0085 
0086     MD5Final(hash, &md5);
0087 
0088     close(in);
0089 
0090     printf("MD5 (%s) = ", *argv);
0091     for (h = 0; h < sizeof(hash); ++h)
0092       printf("%02x", (int) hash[h]);
0093     printf("\n");
0094 
0095     --argc;
0096     ++argv;
0097   }
0098 
0099   free(buffer);
0100 
0101   return 0;
0102 }
0103 
0104 rtems_shell_cmd_t rtems_shell_MD5_Command = {
0105   "md5",                 /* name */
0106   "md5 [file ...]",      /* usage */
0107   "files",               /* topic */
0108   rtems_shell_main_md5,  /* command */
0109   NULL,                  /* alias */
0110   NULL                   /* next */
0111 };