blob: eb39bd9bb23e5d90023de3f66e01f7ba744d9b0a [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcServer"
18
Steven Morelandc5032042021-09-30 15:40:27 -070019#include <inttypes.h>
Steven Moreland798e0d12021-07-14 23:19:25 +000020#include <poll.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000021#include <sys/socket.h>
22#include <sys/un.h>
23
Steven Morelandf137de92021-04-24 01:54:26 +000024#include <thread>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <vector>
26
Steven Moreland826367f2021-09-10 14:05:31 -070027#include <android-base/file.h>
28#include <android-base/hex.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000029#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/Parcel.h>
31#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070032#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <log/log.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000034#include <utils/Compat.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000035
Yifan Hong8c950422021-08-05 17:13:55 -070036#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000037#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070038#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000039#include "RpcWireFormat.h"
40
41namespace android {
42
Steven Morelandc5032042021-09-30 15:40:27 -070043constexpr size_t kSessionIdBytes = 32;
44
Steven Moreland5802c2b2021-05-12 20:13:04 +000045using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000046using base::unique_fd;
47
Yifan Hongecf937d2021-08-11 17:29:28 -070048RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070049RpcServer::~RpcServer() {
50 (void)shutdown();
51}
Steven Moreland5553ac42020-11-11 02:14:45 +000052
Yifan Hong702115c2021-06-24 15:39:18 -070053sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
54 // Default is without TLS.
55 if (rpcTransportCtxFactory == nullptr)
56 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070057 auto ctx = rpcTransportCtxFactory->newServerCtx();
58 if (ctx == nullptr) return nullptr;
59 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000060}
61
Steven Moreland2372f9d2021-08-05 15:42:01 -070062status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000063 return setupSocketServer(UnixSocketAddress(path));
64}
65
Steven Moreland2372f9d2021-08-05 15:42:01 -070066status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000067 // realizing value w/ this type at compile time to avoid ubsan abort
68 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
69
70 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
71}
72
Steven Moreland2372f9d2021-08-05 15:42:01 -070073status_t RpcServer::setupInetServer(const char* address, unsigned int port,
74 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000075 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000076 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070077 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000078 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000079 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070080 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000081 continue;
82 }
83
84 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
85 sockaddr_in addr{};
86 socklen_t len = sizeof(addr);
87 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
88 int savedErrno = errno;
89 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
90 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070091 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000092 }
93 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
94 static_cast<size_t>(len), sizeof(addr));
95 unsigned int realPort = ntohs(addr.sin_port);
96 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
97 "Requesting inet server on %s but it is set up on %u.",
98 socketAddress.toString().c_str(), realPort);
99
100 if (assignedPort != nullptr) {
101 *assignedPort = realPort;
102 }
103
Steven Moreland2372f9d2021-08-05 15:42:01 -0700104 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000105 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000106 ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", address,
Steven Moreland611d15f2021-05-01 01:28:27 +0000107 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700108 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000109}
110
Steven Morelandf137de92021-04-24 01:54:26 +0000111void RpcServer::setMaxThreads(size_t threads) {
112 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700113 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000114 mMaxThreads = threads;
115}
116
117size_t RpcServer::getMaxThreads() {
118 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119}
120
Steven Morelandbf57bce2021-07-26 15:26:12 -0700121void RpcServer::setProtocolVersion(uint32_t version) {
122 mProtocolVersion = version;
123}
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000126 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700127 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700128 mRootObjectWeak = mRootObject = binder;
129}
130
131void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
132 std::lock_guard<std::mutex> _l(mLock);
133 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700134 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700135 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000136}
Steven Moreland51c44a92021-10-14 16:50:35 -0700137void RpcServer::setPerSessionRootObject(
138 std::function<sp<IBinder>(const sockaddr*, socklen_t)>&& makeObject) {
139 std::lock_guard<std::mutex> _l(mLock);
140 mRootObject.clear();
141 mRootObjectWeak.clear();
142 mRootObjectFactory = std::move(makeObject);
143}
Steven Moreland5553ac42020-11-11 02:14:45 +0000144
145sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000146 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700147 bool hasWeak = mRootObjectWeak.unsafe_get();
148 sp<IBinder> ret = mRootObjectWeak.promote();
149 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
150 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000151}
152
Yifan Hong9734cfc2021-09-13 16:14:09 -0700153std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700154 std::lock_guard<std::mutex> _l(mLock);
155 return mCtx->getCertificate(format);
156}
157
Yifan Hong326afd12021-05-19 15:24:54 -0700158static void joinRpcServer(sp<RpcServer>&& thiz) {
159 thiz->join();
160}
161
162void RpcServer::start() {
Yifan Hong326afd12021-05-19 15:24:54 -0700163 std::lock_guard<std::mutex> _l(mLock);
164 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
165 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
166}
167
Steven Moreland611d15f2021-05-01 01:28:27 +0000168void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700169
170 {
171 std::lock_guard<std::mutex> _l(mLock);
172 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
173 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
174 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700175 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700176 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000177 }
Yifan Hong1a235852021-05-13 16:07:47 -0700178
Steven Moreland2b4f3802021-05-22 01:46:27 +0000179 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000180 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700181 sockaddr_storage addr;
182 socklen_t addrLen = sizeof(addr);
183
184 unique_fd clientFd(
185 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(&addr),
186 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
187
188 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(addr)), "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000189
190 if (clientFd < 0) {
191 ALOGE("Could not accept4 socket: %s", strerror(errno));
192 continue;
193 }
194 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
195
196 {
197 std::lock_guard<std::mutex> _l(mLock);
198 std::thread thread =
199 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
Steven Moreland51c44a92021-10-14 16:50:35 -0700200 std::move(clientFd), addr, addrLen);
Steven Moreland410325a2021-06-02 18:37:42 +0000201 mConnectingThreads[thread.get_id()] = std::move(thread);
202 }
Yifan Hong1a235852021-05-13 16:07:47 -0700203 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000204 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700205
206 {
207 std::lock_guard<std::mutex> _l(mLock);
208 mJoinThreadRunning = false;
209 }
210 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000211}
212
Yifan Hong1a235852021-05-13 16:07:47 -0700213bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700214 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000215 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000216 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000217 return false;
218 }
Yifan Hong1a235852021-05-13 16:07:47 -0700219
220 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700221
Steven Morelanda8b44292021-06-08 01:27:53 +0000222 for (auto& [id, session] : mSessions) {
223 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700224 // server lock is a more general lock
225 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000226 session->mShutdownTrigger->trigger();
227 }
228
Steven Morelandee3f4662021-05-22 01:07:33 +0000229 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000230 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
231 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
232 "Connecting threads: "
233 "%zu, Sessions: %zu. Is your server deadlocked?",
234 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
235 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000236 }
Yifan Hong1a235852021-05-13 16:07:47 -0700237
Yifan Hong326afd12021-05-19 15:24:54 -0700238 // At this point, we know join() is about to exit, but the thread that calls
239 // join() may not have exited yet.
240 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
241 // otherwise ~thread() may call std::terminate(), which may crash the process.
242 // If RpcServer does not own the join thread (aka join() is called directly),
243 // then the owner of RpcServer is responsible for cleaning up that thread.
244 if (mJoinThread.get()) {
245 mJoinThread->join();
246 mJoinThread.reset();
247 }
248
Steven Moreland1c943ec2021-07-13 23:57:56 +0000249 LOG_RPC_DETAIL("Finished waiting on shutdown.");
250
Yifan Hong1a235852021-05-13 16:07:47 -0700251 mShutdownTrigger = nullptr;
252 return true;
253}
254
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000256 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257 std::vector<sp<RpcSession>> sessions;
258 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000259 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000261 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000263}
264
Steven Morelandd539fbf2021-05-05 23:40:25 +0000265size_t RpcServer::numUninitializedSessions() {
266 std::lock_guard<std::mutex> _l(mLock);
267 return mConnectingThreads.size();
268}
269
Steven Moreland51c44a92021-10-14 16:50:35 -0700270void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
271 const sockaddr_storage addr, socklen_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000272 // mShutdownTrigger can only be cleared once connection threads have joined.
273 // It must be set before this thread is started
274 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700275 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
276
277 status_t status = OK;
278
279 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700280 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700281 if (client == nullptr) {
282 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
283 status = DEAD_OBJECT;
284 // still need to cleanup before we can return
285 } else {
286 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
287 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000288
Steven Moreland659416d2021-05-11 00:47:50 +0000289 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700290 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000291 iovec iov{&header, sizeof(header)};
292 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1, {});
Yifan Hong702115c2021-06-24 15:39:18 -0700293 if (status != OK) {
294 ALOGE("Failed to read ID for client connecting to RPC server: %s",
295 statusToString(status).c_str());
296 // still need to cleanup before we can return
297 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000298 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700299
Steven Moreland826367f2021-09-10 14:05:31 -0700300 std::vector<uint8_t> sessionId;
301 if (status == OK) {
302 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700303 if (header.sessionIdSize == kSessionIdBytes) {
304 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000305 iovec iov{sessionId.data(), sessionId.size()};
306 status =
307 client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1, {});
Steven Morelandc5032042021-09-30 15:40:27 -0700308 if (status != OK) {
309 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
310 statusToString(status).c_str());
311 // still need to cleanup before we can return
312 }
313 } else {
314 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
315 kSessionIdBytes, header.sessionIdSize);
316 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700317 }
318 }
319 }
320
Steven Morelandbf57bce2021-07-26 15:26:12 -0700321 bool incoming = false;
322 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700323 bool requestingNewSession = false;
324
325 if (status == OK) {
326 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
327 protocolVersion = std::min(header.version,
328 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700329 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700330
331 if (requestingNewSession) {
332 RpcNewSessionResponse response{
333 .version = protocolVersion,
334 };
335
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000336 iovec iov{&response, sizeof(response)};
337 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1, {});
Steven Morelandbf57bce2021-07-26 15:26:12 -0700338 if (status != OK) {
339 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
340 // still need to cleanup before we can return
341 }
342 }
343 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000344
345 std::thread thisThread;
346 sp<RpcSession> session;
347 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000348 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000349
Yifan Hongb3005502021-05-19 15:37:00 -0700350 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
351 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000352 "Must establish connection on owned thread");
353 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000354 ScopeGuard detachGuard = [&]() {
355 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000356 _l.unlock();
357 server->mShutdownCv.notify_all();
358 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000359 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000360
Steven Morelandbf57bce2021-07-26 15:26:12 -0700361 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000362 return;
363 }
364
Steven Morelandbf57bce2021-07-26 15:26:12 -0700365 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000366 if (incoming) {
367 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000368 return;
369 }
370
Steven Moreland826367f2021-09-10 14:05:31 -0700371 // Uniquely identify session at the application layer. Even if a
372 // client/server use the same certificates, if they create multiple
373 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700374 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000375 size_t tries = 0;
376 do {
377 // don't block if there is some entropy issue
378 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700379 ALOGE("Cannot find new address: %s",
380 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000381 return;
382 }
383
Steven Moreland826367f2021-09-10 14:05:31 -0700384 base::unique_fd fd(TEMP_FAILURE_RETRY(
385 open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
386 if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
387 ALOGE("Could not read from /dev/urandom to create session ID");
388 return;
389 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000390 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000391
392 session = RpcSession::make();
Yifan Hong10423062021-10-08 16:26:32 -0700393 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700394 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700395
396 // if null, falls back to server root
397 sp<IBinder> sessionSpecificRoot;
398 if (server->mRootObjectFactory != nullptr) {
399 sessionSpecificRoot =
400 server->mRootObjectFactory(reinterpret_cast<const sockaddr*>(&addr),
401 addrLen);
402 if (sessionSpecificRoot == nullptr) {
403 ALOGE("Warning: server returned null from root object factory");
404 }
405 }
406
Steven Morelanda8b44292021-06-08 01:27:53 +0000407 if (!session->setForServer(server,
408 sp<RpcServer::EventListener>::fromExisting(
409 static_cast<RpcServer::EventListener*>(
410 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700411 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000412 ALOGE("Failed to attach server to session");
413 return;
414 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000415
Steven Moreland01a6bad2021-06-11 00:59:20 +0000416 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000417 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000418 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700419 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000420 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700421 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000422 return;
423 }
424 session = it->second;
425 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000426
Steven Moreland1b304292021-07-15 22:59:34 +0000427 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700428 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000429 "server state must already be initialized");
430 return;
431 }
432
Steven Moreland5802c2b2021-05-12 20:13:04 +0000433 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000434 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000435 }
436
Yifan Hong702115c2021-06-24 15:39:18 -0700437 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000438
Steven Morelanda63ff932021-05-12 00:03:15 +0000439 // avoid strong cycle
440 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000441
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000442 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000443}
444
Steven Moreland2372f9d2021-08-05 15:42:01 -0700445status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000446 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700447 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000448
Yifan Hongb675ffe2021-08-05 16:37:17 -0700449 unique_fd serverFd(TEMP_FAILURE_RETRY(
450 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000451 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700452 int savedErrno = errno;
453 ALOGE("Could not create socket: %s", strerror(savedErrno));
454 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000455 }
456
457 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
458 int savedErrno = errno;
459 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700460 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000461 }
462
Yifan Honge96a1f12021-07-13 16:08:28 -0700463 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
464 // the backlog is increased to a large number.
465 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
466 // to 1.
467 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000468 int savedErrno = errno;
469 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700470 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000471 }
472
Steven Moreland704fc1a2021-05-04 23:13:14 +0000473 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
474
Steven Moreland2372f9d2021-08-05 15:42:01 -0700475 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700476 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700477 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700478 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000480}
481
Steven Morelanddd67b942021-07-23 17:15:41 -0700482void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700483 const std::vector<uint8_t>& id = session->mId;
484 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
485 LOG_RPC_DETAIL("Dropping session with address %s",
486 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000487
488 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700489 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000490 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700491 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000492 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700493 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000494 (void)mSessions.erase(it);
495}
496
Steven Moreland19fc9f72021-06-10 03:57:30 +0000497void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000498 mShutdownCv.notify_all();
499}
500
Yifan Hong0eb5a672021-05-12 18:00:25 -0700501bool RpcServer::hasServer() {
502 std::lock_guard<std::mutex> _l(mLock);
503 return mServer.ok();
504}
505
Yifan Hong00aeb762021-05-12 17:07:36 -0700506unique_fd RpcServer::releaseServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700507 std::lock_guard<std::mutex> _l(mLock);
508 return std::move(mServer);
509}
510
Steven Moreland2372f9d2021-08-05 15:42:01 -0700511status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700512 std::lock_guard<std::mutex> _l(mLock);
513 if (mServer.ok()) {
514 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700515 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700516 }
517 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700518 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700519}
520
Steven Moreland5553ac42020-11-11 02:14:45 +0000521} // namespace android