2 * QEMU Random Number Generator Backend
4 * Copyright IBM, Corp. 2012
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
14 #include "sysemu/rng-random.h"
15 #include "sysemu/rng.h"
16 #include "qapi/qmp/qerror.h"
17 #include "qemu/main-loop.h"
26 EntropyReceiveFunc
*receive_func
;
32 * A simple and incomplete backend to request entropy from /dev/random.
34 * This backend exposes an additional "filename" property that can be used to
35 * set the filename to use to open the backend.
38 static void entropy_available(void *opaque
)
40 RndRandom
*s
= RNG_RANDOM(opaque
);
41 uint8_t buffer
[s
->size
];
44 len
= read(s
->fd
, buffer
, s
->size
);
45 if (len
< 0 && errno
== EAGAIN
) {
50 s
->receive_func(s
->opaque
, buffer
, len
);
51 s
->receive_func
= NULL
;
53 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
56 static void rng_random_request_entropy(RngBackend
*b
, size_t size
,
57 EntropyReceiveFunc
*receive_entropy
,
60 RndRandom
*s
= RNG_RANDOM(b
);
62 if (s
->receive_func
) {
63 s
->receive_func(s
->opaque
, NULL
, 0);
66 s
->receive_func
= receive_entropy
;
70 qemu_set_fd_handler(s
->fd
, entropy_available
, NULL
, s
);
73 static void rng_random_opened(RngBackend
*b
, Error
**errp
)
75 RndRandom
*s
= RNG_RANDOM(b
);
77 if (s
->filename
== NULL
) {
78 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
79 "filename", "a valid filename");
81 s
->fd
= qemu_open(s
->filename
, O_RDONLY
| O_NONBLOCK
);
83 error_setg_file_open(errp
, errno
, s
->filename
);
88 static char *rng_random_get_filename(Object
*obj
, Error
**errp
)
90 RndRandom
*s
= RNG_RANDOM(obj
);
92 return g_strdup(s
->filename
);
95 static void rng_random_set_filename(Object
*obj
, const char *filename
,
98 RngBackend
*b
= RNG_BACKEND(obj
);
99 RndRandom
*s
= RNG_RANDOM(obj
);
102 error_setg(errp
, QERR_PERMISSION_DENIED
);
107 s
->filename
= g_strdup(filename
);
110 static void rng_random_init(Object
*obj
)
112 RndRandom
*s
= RNG_RANDOM(obj
);
114 object_property_add_str(obj
, "filename",
115 rng_random_get_filename
,
116 rng_random_set_filename
,
119 s
->filename
= g_strdup("/dev/random");
123 static void rng_random_finalize(Object
*obj
)
125 RndRandom
*s
= RNG_RANDOM(obj
);
128 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
135 static void rng_random_class_init(ObjectClass
*klass
, void *data
)
137 RngBackendClass
*rbc
= RNG_BACKEND_CLASS(klass
);
139 rbc
->request_entropy
= rng_random_request_entropy
;
140 rbc
->opened
= rng_random_opened
;
143 static const TypeInfo rng_random_info
= {
144 .name
= TYPE_RNG_RANDOM
,
145 .parent
= TYPE_RNG_BACKEND
,
146 .instance_size
= sizeof(RndRandom
),
147 .class_init
= rng_random_class_init
,
148 .instance_init
= rng_random_init
,
149 .instance_finalize
= rng_random_finalize
,
152 static void register_types(void)
154 type_register_static(&rng_random_info
);
157 type_init(register_types
);