libbinder: move session ID RNG code to Utils.cpp
This moves the code that reads from /dev/urandom from RpcServer.cpp
into Utils.cpp so other operating systems can provide their own
implementations by replacing Utils.cpp.
Test: atest binderRpcTest
Bug: 224644083
Change-Id: I2923b25537c07060b830b0d8378df8c969bbd02f
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index eb39bd9..d63c3f1 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -24,7 +24,6 @@
#include <thread>
#include <vector>
-#include <android-base/file.h>
#include <android-base/hex.h>
#include <android-base/scopeguard.h>
#include <binder/Parcel.h>
@@ -37,6 +36,7 @@
#include "RpcSocketAddress.h"
#include "RpcState.h"
#include "RpcWireFormat.h"
+#include "Utils.h"
namespace android {
@@ -381,10 +381,9 @@
return;
}
- base::unique_fd fd(TEMP_FAILURE_RETRY(
- open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
- if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
- ALOGE("Could not read from /dev/urandom to create session ID");
+ auto status = getRandomBytes(sessionId.data(), sessionId.size());
+ if (status != OK) {
+ ALOGE("Failed to read random session ID: %s", strerror(-status));
return;
}
} while (server->mSessions.end() != server->mSessions.find(sessionId));
diff --git a/libs/binder/Utils.cpp b/libs/binder/Utils.cpp
index d2a5be1..b0289a7 100644
--- a/libs/binder/Utils.cpp
+++ b/libs/binder/Utils.cpp
@@ -16,6 +16,7 @@
#include "Utils.h"
+#include <android-base/file.h>
#include <string.h>
using android::base::ErrnoError;
@@ -38,4 +39,17 @@
return {};
}
+status_t getRandomBytes(uint8_t* data, size_t size) {
+ int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
+ if (ret == -1) {
+ return -errno;
+ }
+
+ base::unique_fd fd(ret);
+ if (!base::ReadFully(fd, data, size)) {
+ return -errno;
+ }
+ return OK;
+}
+
} // namespace android
diff --git a/libs/binder/Utils.h b/libs/binder/Utils.h
index ff2fad8..150d520 100644
--- a/libs/binder/Utils.h
+++ b/libs/binder/Utils.h
@@ -20,6 +20,7 @@
#include <android-base/result.h>
#include <android-base/unique_fd.h>
#include <log/log.h>
+#include <utils/Errors.h>
#define TEST_AND_RETURN(value, expr) \
do { \
@@ -36,4 +37,6 @@
android::base::Result<void> setNonBlocking(android::base::borrowed_fd fd);
+status_t getRandomBytes(uint8_t* data, size_t size);
+
} // namespace android