xref: /titanic_41/usr/src/lib/libwanbootutil/common/wbio.c (revision 7c478bd95313f5f23a4c958a745db2134aa03244)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 
32 #include "wbio.h"
33 
34 /*
35  * Write `buflen' bytes from `buffer' to the file represented by `fd'.
36  * Returns -1 if all `buflen' bytes cannot be written, otherwise returns 0.
37  */
38 int
wbio_nwrite(int fd,const void * buffer,size_t buflen)39 wbio_nwrite(int fd, const void *buffer, size_t buflen)
40 {
41 	size_t		nwritten;
42 	ssize_t		nbytes;
43 	const char	*buf = buffer;
44 
45 	for (nwritten = 0; nwritten < buflen; nwritten += nbytes) {
46 		nbytes = write(fd, &buf[nwritten], buflen - nwritten);
47 		if (nbytes <= 0)
48 			return (-1);
49 	}
50 
51 	return (0);
52 }
53 
54 /*
55  * Read `buflen' bytes into `buffer' from the file represented by `fd'.
56  * Returns -1 if all `buflen' bytes cannot be read, otherwise returns 0.
57  */
58 int
wbio_nread(int fd,void * buffer,size_t buflen)59 wbio_nread(int fd, void *buffer, size_t buflen)
60 {
61 	size_t	nread;
62 	ssize_t	nbytes;
63 	char	*buf = buffer;
64 
65 	for (nread = 0; nread < buflen; nread += nbytes) {
66 		nbytes = read(fd, &buf[nread], buflen - nread);
67 		if (nbytes <= 0)
68 			return (-1);
69 	}
70 
71 	return (0);
72 }
73 
74 /*
75  * Read a random number of `buflen' bytes into `buffer' from /dev/urandom.
76  * Returns -1 if all `buflen' bytes cannot be read, otherwise returns 0.
77  */
78 int
wbio_nread_rand(void * buffer,size_t buflen)79 wbio_nread_rand(void *buffer, size_t buflen)
80 {
81 	int fd;
82 
83 	if ((fd = open("/dev/urandom", O_RDONLY)) == -1) {
84 		return (-1);
85 	}
86 
87 	if (wbio_nread(fd, buffer, buflen) != 0) {
88 		(void) close(fd);
89 		return (-1);
90 	}
91 
92 	(void) close(fd);
93 	return (0);
94 }
95