rumpuser_random.c revision 1.2.2.2 1 /*
2 * Copyright (c) 2014 Justin Cormack. All Rights Reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
14 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26 #include "rumpuser_port.h"
27
28 #if !defined(lint)
29 __RCSID("$NetBSD: rumpuser_random.c,v 1.2.2.2 2014/08/10 06:52:26 tls Exp $");
30 #endif /* !lint */
31
32 #include <sys/types.h>
33
34 #include <assert.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42
43 #include <rump/rumpuser.h>
44
45 #include "rumpuser_int.h"
46
47 static const size_t random_maxread = 32;
48
49 #ifdef PLATFORM_HAS_ARC4RANDOM_BUF
50 int
51 rumpuser__random_init(void)
52 {
53
54 return 0;
55 }
56 #else
57 static const char *random_device = "/dev/urandom";
58 static int random_fd = -1;
59
60 int
61 rumpuser__random_init(void)
62 {
63
64 random_fd = open(random_device, O_RDONLY);
65 if (random_fd < 0) {
66 fprintf(stderr, "random init open failed\n");
67 return errno;
68 }
69 return 0;
70 }
71 #endif
72
73 int
74 rumpuser_getrandom(void *buf, size_t buflen, int flags, size_t *retp)
75 {
76 #ifndef PLATFORM_HAS_ARC4RANDOM_BUF
77 ssize_t rv;
78
79 rv = read(random_fd, buf, buflen > random_maxread ? random_maxread : buflen);
80 if (rv < 0) {
81 ET(errno);
82 }
83 *retp = rv;
84 #else
85 buflen = buflen > random_maxread ? random_maxread : buflen;
86 arc4random_buf(buf, buflen);
87 *retp = buflen;
88 #endif
89
90 return 0;
91 }
92