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/rng-random.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
);
46 s
->receive_func(s
->opaque
, buffer
, len
);
47 s
->receive_func
= NULL
;
49 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
52 static void rng_random_request_entropy(RngBackend
*b
, size_t size
,
53 EntropyReceiveFunc
*receive_entropy
,
56 RndRandom
*s
= RNG_RANDOM(b
);
58 if (s
->receive_func
) {
59 s
->receive_func(s
->opaque
, NULL
, 0);
62 s
->receive_func
= receive_entropy
;
66 qemu_set_fd_handler(s
->fd
, entropy_available
, NULL
, s
);
69 static void rng_random_opened(RngBackend
*b
, Error
**errp
)
71 RndRandom
*s
= RNG_RANDOM(b
);
73 if (s
->filename
== NULL
) {
74 error_set(errp
, QERR_INVALID_PARAMETER_VALUE
,
75 "filename", "a valid filename");
77 s
->fd
= open(s
->filename
, O_RDONLY
| O_NONBLOCK
);
80 error_set(errp
, QERR_OPEN_FILE_FAILED
, s
->filename
);
85 static char *rng_random_get_filename(Object
*obj
, Error
**errp
)
87 RndRandom
*s
= RNG_RANDOM(obj
);
90 return g_strdup(s
->filename
);
96 static void rng_random_set_filename(Object
*obj
, const char *filename
,
99 RngBackend
*b
= RNG_BACKEND(obj
);
100 RndRandom
*s
= RNG_RANDOM(obj
);
103 error_set(errp
, QERR_PERMISSION_DENIED
);
111 s
->filename
= g_strdup(filename
);
114 static void rng_random_init(Object
*obj
)
116 RndRandom
*s
= RNG_RANDOM(obj
);
118 object_property_add_str(obj
, "filename",
119 rng_random_get_filename
,
120 rng_random_set_filename
,
123 s
->filename
= g_strdup("/dev/random");
126 static void rng_random_finalize(Object
*obj
)
128 RndRandom
*s
= RNG_RANDOM(obj
);
130 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
139 static void rng_random_class_init(ObjectClass
*klass
, void *data
)
141 RngBackendClass
*rbc
= RNG_BACKEND_CLASS(klass
);
143 rbc
->request_entropy
= rng_random_request_entropy
;
144 rbc
->opened
= rng_random_opened
;
147 static const TypeInfo rng_random_info
= {
148 .name
= TYPE_RNG_RANDOM
,
149 .parent
= TYPE_RNG_BACKEND
,
150 .instance_size
= sizeof(RndRandom
),
151 .class_init
= rng_random_class_init
,
152 .instance_init
= rng_random_init
,
153 .instance_finalize
= rng_random_finalize
,
156 static void register_types(void)
158 type_register_static(&rng_random_info
);
161 type_init(register_types
);