utils: export pw_getrandom

Export the symbol and move it to utils.
This commit is contained in:
Wim Taymans 2021-11-09 16:16:30 +01:00
parent 62509f23d7
commit daf761a87f
3 changed files with 37 additions and 23 deletions

View file

@ -25,34 +25,12 @@
#include "config.h"
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#ifndef ENODATA
#define ENODATA 9919
#endif
#if HAVE_SYS_RANDOM_H
#include <sys/random.h>
#endif
static ssize_t pw_getrandom(void *buf, size_t buflen, unsigned int flags) {
ssize_t bytes;
#ifdef HAVE_GETRANDOM
bytes = getrandom(buf, buflen ,flags);
if (!(bytes == -1 && errno == ENOSYS))
return bytes;
#endif
int fd = open("/dev/urandom", O_CLOEXEC);
if (fd < 0)
return -1;
bytes = read(fd, buf, buflen);
close(fd);
return bytes;
}
#include <spa/utils/string.h>
#include <spa/debug/types.h>
#include <spa/utils/string.h>
#include "pipewire/impl.h"
#include "pipewire/private.h"

View file

@ -22,6 +22,14 @@
* DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#if HAVE_SYS_RANDOM_H
#include <sys/random.h>
#endif
#include <string.h>
#include <pipewire/array.h>
@ -133,3 +141,30 @@ char *pw_strip(char *str, const char *whitespace)
return str;
}
/** Fill a buffer with random data
* \param buf a buffer to fill
* \param buflen the number of bytes to fill
* \param flags optional flags
* \return the number of bytes filled
*
* Fill \a buf with \a buflen random bytes.
*/
SPA_EXPORT
ssize_t pw_getrandom(void *buf, size_t buflen, unsigned int flags)
{
ssize_t bytes;
#ifdef HAVE_GETRANDOM
bytes = getrandom(buf, buflen, flags);
if (!(bytes == -1 && errno == ENOSYS))
return bytes;
#endif
int fd = open("/dev/urandom", O_CLOEXEC);
if (fd < 0)
return -1;
bytes = read(fd, buf, buflen);
close(fd);
return bytes;
}

View file

@ -85,6 +85,7 @@ pw_strip(char *str, const char *whitespace);
})
#endif
ssize_t pw_getrandom(void *buf, size_t buflen, unsigned int flags);
/**
* \}
*/