]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libmd/mdXhl.c
Add cross-references for the new kldsym(2) man page.
[FreeBSD/FreeBSD.git] / lib / libmd / mdXhl.c
1 /* mdXhl.c
2  * ----------------------------------------------------------------------------
3  * "THE BEER-WARE LICENSE" (Revision 42):
4  * <phk@login.dkuug.dk> wrote this file.  As long as you retain this notice you
5  * can do whatever you want with this stuff. If we meet some day, and you think
6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7  * ----------------------------------------------------------------------------
8  *
9  * $FreeBSD$
10  *
11  */
12
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16 #include <unistd.h>
17
18 #include <errno.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21
22 #include "mdX.h"
23
24 char *
25 MDXEnd(MDX_CTX *ctx, char *buf)
26 {
27     int i;
28     unsigned char digest[LENGTH];
29     static const char hex[]="0123456789abcdef";
30
31     if (!buf)
32         buf = malloc(2*LENGTH + 1);
33     if (!buf)
34         return 0;
35     MDXFinal(digest, ctx);
36     for (i = 0; i < LENGTH; i++) {
37         buf[i+i] = hex[digest[i] >> 4];
38         buf[i+i+1] = hex[digest[i] & 0x0f];
39     }
40     buf[i+i] = '\0';
41     return buf;
42 }
43
44 char *
45 MDXFile(const char *filename, char *buf)
46 {
47     return MDXFileChunk(filename, buf, 0, 0);
48 }
49
50 char *
51 MDXFileChunk(const char *filename, char *buf, off_t ofs, off_t len)
52 {
53     unsigned char buffer[BUFSIZ];
54     MDX_CTX ctx;
55     struct stat stbuf;
56     int f, i, e;
57     off_t n;
58
59     MDXInit(&ctx);
60     f = open(filename, O_RDONLY);
61     if (f < 0) return 0;
62     if (fstat(f, &stbuf) < 0) return 0;
63     if (ofs > stbuf.st_size)
64         ofs = stbuf.st_size;
65     if ((len == 0) || (len > stbuf.st_size - ofs))
66         len = stbuf.st_size - ofs;
67     if (lseek(f, ofs, SEEK_SET) < 0) return 0;
68     n = len;
69     while (n > 0) {
70         if (n > sizeof(buffer))
71             i = read(f, buffer, sizeof(buffer));
72         else
73             i = read(f, buffer, n);
74         if (i < 0) break;
75         MDXUpdate(&ctx, buffer, i);
76         n -= i;
77     } 
78     e = errno;
79     close(f);
80     errno = e;
81     if (i < 0) return 0;
82     return MDXEnd(&ctx, buf);
83 }
84
85 char *
86 MDXData (const unsigned char *data, unsigned int len, char *buf)
87 {
88     MDX_CTX ctx;
89
90     MDXInit(&ctx);
91     MDXUpdate(&ctx,data,len);
92     return MDXEnd(&ctx, buf);
93 }