36d5446b8865d921e7ac1299c624cd78b6c838ad
[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 <utils/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, bool,
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 return TRUE;
63 }
64
65 METHOD(rng_t, allocate_bytes, bool,
66 private_random_rng_t *this, size_t bytes, chunk_t *chunk)
67 {
68 *chunk = chunk_alloc(bytes);
69 get_bytes(this, chunk->len, chunk->ptr);
70 return TRUE;
71 }
72
73 METHOD(rng_t, destroy, void,
74 private_random_rng_t *this)
75 {
76 free(this);
77 }
78
79 /*
80 * Described in header.
81 */
82 random_rng_t *random_rng_create(rng_quality_t quality)
83 {
84 private_random_rng_t *this;
85
86 INIT(this,
87 .public = {
88 .rng = {
89 .get_bytes = _get_bytes,
90 .allocate_bytes = _allocate_bytes,
91 .destroy = _destroy,
92 },
93 },
94 );
95
96 switch (quality)
97 {
98 case RNG_TRUE:
99 this->fd = random_plugin_get_dev_random();
100 break;
101 case RNG_STRONG:
102 this->fd = random_plugin_get_strong_equals_true() ?
103 random_plugin_get_dev_random() :
104 random_plugin_get_dev_urandom();
105 break;
106 case RNG_WEAK:
107 default:
108 this->fd = random_plugin_get_dev_urandom();
109 break;
110 }
111
112 return &this->public;
113 }
114