xref: /freebsd/lib/libmd/mdXhl.c (revision 3311ff84eac3b7e82f28e331df0586036c6d361c)
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 		i = -1;
64 		goto error;
65 	}
66 	if (ofs > stbuf.st_size)
67 		ofs = stbuf.st_size;
68 	if ((len == 0) || (len > stbuf.st_size - ofs))
69 		len = stbuf.st_size - ofs;
70 	if (lseek(f, ofs, SEEK_SET) < 0) {
71 		i = -1;
72 		goto error;
73 	}
74 	n = len;
75 	i = 0;
76 	while (n > 0) {
77 		if (n > sizeof(buffer))
78 			i = read(f, buffer, sizeof(buffer));
79 		else
80 			i = read(f, buffer, n);
81 		if (i <= 0)
82 			break;
83 		MDXUpdate(&ctx, buffer, i);
84 		n -= i;
85 	}
86 error:
87 	e = errno;
88 	close(f);
89 	errno = e;
90 	if (i < 0)
91 		return 0;
92 	return (MDXEnd(&ctx, buf));
93 }
94 
95 char *
96 MDXData (const void *data, unsigned int len, char *buf)
97 {
98 	MDX_CTX ctx;
99 
100 	MDXInit(&ctx);
101 	MDXUpdate(&ctx,data,len);
102 	return (MDXEnd(&ctx, buf));
103 }
104 
105 #ifdef WEAK_REFS
106 /* When building libmd, provide weak references. Note: this is not
107    activated in the context of compiling these sources for internal
108    use in libcrypt.
109  */
110 #undef MDXEnd
111 __weak_reference(_libmd_MDXEnd, MDXEnd);
112 #undef MDXFile
113 __weak_reference(_libmd_MDXFile, MDXFile);
114 #undef MDXFileChunk
115 __weak_reference(_libmd_MDXFileChunk, MDXFileChunk);
116 #undef MDXData
117 __weak_reference(_libmd_MDXData, MDXData);
118 #endif
119