1 /* mdXhl.c * ---------------------------------------------------------------------------- 2 * "THE BEER-WARE LICENSE" (Revision 42): 3 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you 4 * can do whatever you want with this stuff. If we meet some day, and you think 5 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp 6 * ---------------------------------------------------------------------------- 7 */ 8 9 #include <sys/cdefs.h> 10 __FBSDID("$FreeBSD$"); 11 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <unistd.h> 16 17 #include <errno.h> 18 #include <stdio.h> 19 #include <stdlib.h> 20 21 #include "mdX.h" 22 23 char * 24 MDXEnd(MDX_CTX *ctx, char *buf) 25 { 26 int i; 27 unsigned char digest[LENGTH]; 28 static const char hex[]="0123456789abcdef"; 29 30 if (!buf) 31 buf = malloc(2*LENGTH + 1); 32 if (!buf) 33 return 0; 34 MDXFinal(digest, ctx); 35 for (i = 0; i < LENGTH; i++) { 36 buf[i+i] = hex[digest[i] >> 4]; 37 buf[i+i+1] = hex[digest[i] & 0x0f]; 38 } 39 buf[i+i] = '\0'; 40 return buf; 41 } 42 43 char * 44 MDXFile(const char *filename, char *buf) 45 { 46 return (MDXFileChunk(filename, buf, 0, 0)); 47 } 48 49 char * 50 MDXFileChunk(const char *filename, char *buf, off_t ofs, off_t len) 51 { 52 unsigned char buffer[16*1024]; 53 MDX_CTX ctx; 54 struct stat stbuf; 55 int f, i, e; 56 off_t n; 57 58 MDXInit(&ctx); 59 f = open(filename, O_RDONLY); 60 if (f < 0) 61 return 0; 62 if (fstat(f, &stbuf) < 0) 63 return 0; 64 if (ofs > stbuf.st_size) 65 ofs = stbuf.st_size; 66 if ((len == 0) || (len > stbuf.st_size - ofs)) 67 len = stbuf.st_size - ofs; 68 if (lseek(f, ofs, SEEK_SET) < 0) 69 return 0; 70 n = len; 71 i = 0; 72 while (n > 0) { 73 if (n > sizeof(buffer)) 74 i = read(f, buffer, sizeof(buffer)); 75 else 76 i = read(f, buffer, n); 77 if (i <= 0) 78 break; 79 MDXUpdate(&ctx, buffer, i); 80 n -= i; 81 } 82 e = errno; 83 close(f); 84 errno = e; 85 if (i < 0) 86 return 0; 87 return (MDXEnd(&ctx, buf)); 88 } 89 90 char * 91 MDXData (const void *data, unsigned int len, char *buf) 92 { 93 MDX_CTX ctx; 94 95 MDXInit(&ctx); 96 MDXUpdate(&ctx,data,len); 97 return (MDXEnd(&ctx, buf)); 98 } 99 100 #ifdef WEAK_REFS 101 /* When building libmd, provide weak references. Note: this is not 102 activated in the context of compiling these sources for internal 103 use in libcrypt. 104 */ 105 #undef MDXEnd 106 __weak_reference(_libmd_MDXEnd, MDXEnd); 107 #undef MDXFile 108 __weak_reference(_libmd_MDXFile, MDXFile); 109 #undef MDXFileChunk 110 __weak_reference(_libmd_MDXFileChunk, MDXFileChunk); 111 #undef MDXData 112 __weak_reference(_libmd_MDXData, MDXData); 113 #endif 114