4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
29 #include <sys/types.h>
33 #include <cryptoutil.h>
36 * Read file into buffer. Used to read raw key data or initialization
37 * vector data. Buffer must be freed by caller using free().
39 * If file is a regular file, entire file is read and dlen is set
40 * to the number of bytes read. Otherwise, dlen should first be set
41 * to the number of bytes requested and will be reset to actual number
44 * Return 0 on success and errno on error.
47 pkcs11_read_data(char *filename
, void **dbuf
, size_t *dlen
)
56 if (filename
== NULL
|| dbuf
== NULL
|| dlen
== NULL
)
59 if ((fd
= open(filename
, O_RDONLY
| O_NONBLOCK
)) == -1) {
61 cryptoerror(LOG_STDERR
, gettext("cannot open %s"), filename
);
65 if (fstat(fd
, &statbuf
) == -1) {
67 cryptoerror(LOG_STDERR
, gettext("cannot stat %s"), filename
);
71 if (S_ISREG(statbuf
.st_mode
)) {
72 /* read the entire regular file */
73 filesize
= statbuf
.st_size
;
76 /* read requested bytes from special file */
83 * for decrypt this is an error; for digest this is ok;
84 * make it ok here but also set dbuf = NULL and dlen = 0
85 * to indicate there was no data to read and caller can
86 * retranslate that to an error if it wishes.
94 if ((filebuf
= malloc(filesize
)) == NULL
) {
96 cryptoerror(LOG_STDERR
, gettext("malloc: %s"), strerror(ret
));
101 /* either it got read or it didn't */
102 if (read(fd
, filebuf
, filesize
) != filesize
) {
104 cryptoerror(LOG_STDERR
,
105 gettext("error reading file %s: %s"), filename
,
110 /* reading from special file may need some coaxing */
111 char *marker
= (char *)filebuf
;
112 size_t left
= filesize
;
115 for (/* */; left
> 0; marker
+= nread
, left
-= nread
) {
116 /* keep reading it's going well */
117 nread
= read(fd
, marker
, left
);
118 if (nread
> 0 || (nread
== 0 && errno
== EINTR
)) {
123 /* might have to be good enough for caller */
124 if (nread
== 0 && errno
== EAGAIN
)
127 /* anything else is an error */
130 cryptoerror(LOG_STDERR
,
131 gettext("error reading file %s: %s"),
132 filename
, strerror(ret
));
136 /* reset to actual number of bytes read */