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 "sysemu/rng-random.h"
14 #include "sysemu/rng.h"
15 #include "qapi/qmp/qerror.h"
16 #include "qemu/main-loop.h"
25 EntropyReceiveFunc
*receive_func
;
31 * A simple and incomplete backend to request entropy from /dev/random.
33 * This backend exposes an additional "filename" property that can be used to
34 * set the filename to use to open the backend.
37 static void entropy_available(void *opaque
)
39 RndRandom
*s
= RNG_RANDOM(opaque
);
40 uint8_t buffer
[s
->size
];
43 len
= read(s
->fd
, buffer
, s
->size
);
44 if (len
< 0 && errno
== EAGAIN
) {
49 s
->receive_func(s
->opaque
, buffer
, len
);
50 s
->receive_func
= NULL
;
52 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
55 static void rng_random_request_entropy(RngBackend
*b
, size_t size
,
56 EntropyReceiveFunc
*receive_entropy
,
59 RndRandom
*s
= RNG_RANDOM(b
);
61 if (s
->receive_func
) {
62 s
->receive_func(s
->opaque
, NULL
, 0);
65 s
->receive_func
= receive_entropy
;
69 qemu_set_fd_handler(s
->fd
, entropy_available
, NULL
, s
);
72 static void rng_random_opened(RngBackend
*b
, Error
**errp
)
74 RndRandom
*s
= RNG_RANDOM(b
);
76 if (s
->filename
== NULL
) {
77 error_set(errp
, QERR_INVALID_PARAMETER_VALUE
,
78 "filename", "a valid filename");
80 s
->fd
= qemu_open(s
->filename
, O_RDONLY
| O_NONBLOCK
);
82 error_setg_file_open(errp
, errno
, s
->filename
);
87 static char *rng_random_get_filename(Object
*obj
, Error
**errp
)
89 RndRandom
*s
= RNG_RANDOM(obj
);
92 return g_strdup(s
->filename
);
98 static void rng_random_set_filename(Object
*obj
, const char *filename
,
101 RngBackend
*b
= RNG_BACKEND(obj
);
102 RndRandom
*s
= RNG_RANDOM(obj
);
105 error_set(errp
, QERR_PERMISSION_DENIED
);
113 s
->filename
= g_strdup(filename
);
116 static void rng_random_init(Object
*obj
)
118 RndRandom
*s
= RNG_RANDOM(obj
);
120 object_property_add_str(obj
, "filename",
121 rng_random_get_filename
,
122 rng_random_set_filename
,
125 s
->filename
= g_strdup("/dev/random");
128 static void rng_random_finalize(Object
*obj
)
130 RndRandom
*s
= RNG_RANDOM(obj
);
132 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
141 static void rng_random_class_init(ObjectClass
*klass
, void *data
)
143 RngBackendClass
*rbc
= RNG_BACKEND_CLASS(klass
);
145 rbc
->request_entropy
= rng_random_request_entropy
;
146 rbc
->opened
= rng_random_opened
;
149 static const TypeInfo rng_random_info
= {
150 .name
= TYPE_RNG_RANDOM
,
151 .parent
= TYPE_RNG_BACKEND
,
152 .instance_size
= sizeof(RndRandom
),
153 .class_init
= rng_random_class_init
,
154 .instance_init
= rng_random_init
,
155 .instance_finalize
= rng_random_finalize
,
158 static void register_types(void)
160 type_register_static(&rng_random_info
);
163 type_init(register_types
);