42eddbb0985686ca67de3c3f85bd1c102d76f252
[strongswan.git] / src / libstrongswan / plugins / random / random_rng.c
1 /*
2 * Copyright (C) 2005-2008 Martin Willi
3 * Copyright (C) 2005 Jan Hutter
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <string.h>
18 #include <unistd.h>
19 #include <errno.h>
20 #include <debug.h>
21
22 #include "random_rng.h"
23 #include "random_plugin.h"
24
25 typedef struct private_random_rng_t private_random_rng_t;
26
27 /**
28 * Private data of an random_rng_t object.
29 */
30 struct private_random_rng_t {
31
32 /**
33 * Public random_rng_t interface.
34 */
35 random_rng_t public;
36
37 /**
38 * random device, depends on quality
39 */
40 int fd;
41 };
42
43 METHOD(rng_t, get_bytes, void,
44 private_random_rng_t *this, size_t bytes, u_int8_t *buffer)
45 {
46 size_t done;
47 ssize_t got;
48
49 done = 0;
50
51 while (done < bytes)
52 {
53 got = read(this->fd, buffer + done, bytes - done);
54 if (got <= 0)
55 {
56 DBG1(DBG_LIB, "reading from random FD %d failed: %s, retrying...",
57 this->fd, strerror(errno));
58 sleep(1);
59 }
60 done += got;
61 }
62 }
63
64 METHOD(rng_t, allocate_bytes, void,
65 private_random_rng_t *this, size_t bytes, chunk_t *chunk)
66 {
67 *chunk = chunk_alloc(bytes);
68 get_bytes(this, chunk->len, chunk->ptr);
69 }
70
71 METHOD(rng_t, destroy, void,
72 private_random_rng_t *this)
73 {
74 free(this);
75 }
76
77 /*
78 * Described in header.
79 */
80 random_rng_t *random_rng_create(rng_quality_t quality)
81 {
82 private_random_rng_t *this;
83
84 INIT(this,
85 .public = {
86 .rng = {
87 .get_bytes = _get_bytes,
88 .allocate_bytes = _allocate_bytes,
89 .destroy = _destroy,
90 },
91 },
92 );
93
94 switch (quality)
95 {
96 case RNG_TRUE:
97 this->fd = random_plugin_get_dev_random();
98 break;
99 case RNG_STRONG:
100 case RNG_WEAK:
101 default:
102 this->fd = random_plugin_get_dev_urandom();
103 break;
104 }
105
106 return &this->public;
107 }
108