]> git.proxmox.com Git - mirror_ovs.git/blame - lib/entropy.c
xtoxll: Rename "byte-order" since it now include more than xtoxll.
[mirror_ovs.git] / lib / entropy.c
CommitLineData
e251c8d0
BP
1/* Copyright (c) 2008, 2009, 2010 Nicira Networks
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <config.h>
17
18#include "entropy.h"
19
20#include <errno.h>
21#include <fcntl.h>
22#include <unistd.h>
23
24#include "socket-util.h"
25#include "vlog.h"
26
27VLOG_DEFINE_THIS_MODULE(entropy)
28
29static const char urandom[] = "/dev/urandom";
30
31/* Initializes 'buffer' with 'n' bytes of high-quality random numbers. Returns
32 * 0 if successful, otherwise a positive errno value or EOF on error. */
33int
34get_entropy(void *buffer, size_t n)
35{
36 size_t bytes_read;
37 int error;
38 int fd;
39
40 fd = open(urandom, O_RDONLY);
41 if (fd < 0) {
42 VLOG_ERR("%s: open failed (%s)", urandom, strerror(errno));
43 return errno ? errno : EINVAL;
44 }
45
46 error = read_fully(fd, buffer, n, &bytes_read);
47 close(fd);
48
49 if (error) {
50 VLOG_ERR("%s: read error (%s)", urandom,
51 error == EOF ? "unexpected end of file" : strerror(error));
52 }
53 return error;
54}
55
56/* Initializes 'buffer' with 'n' bytes of high-quality random numbers. Exits
57 * if an error occurs. */
58void
59get_entropy_or_die(void *buffer, size_t n)
60{
61 int error = get_entropy(buffer, n);
62 if (error) {
63 ovs_fatal(error, "%s: read error", urandom);
64 }
65}