blob: f2a620d6528b8671223a105fc4cc340a24c96293 [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/hex.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000028#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029#include <binder/Parcel.h>
30#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070031#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <log/log.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000033#include <utils/Compat.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000035#include "BuildFlags.h"
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"
Andrei Homescuc24c8792022-04-19 00:24:51 +000040#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000041
42namespace android {
43
Steven Morelandc5032042021-09-30 15:40:27 -070044constexpr size_t kSessionIdBytes = 32;
45
Steven Moreland5802c2b2021-05-12 20:13:04 +000046using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000047using base::unique_fd;
48
Yifan Hongecf937d2021-08-11 17:29:28 -070049RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070050RpcServer::~RpcServer() {
51 (void)shutdown();
52}
Steven Moreland5553ac42020-11-11 02:14:45 +000053
Yifan Hong702115c2021-06-24 15:39:18 -070054sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
55 // Default is without TLS.
56 if (rpcTransportCtxFactory == nullptr)
57 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070058 auto ctx = rpcTransportCtxFactory->newServerCtx();
59 if (ctx == nullptr) return nullptr;
60 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000061}
62
Steven Moreland2372f9d2021-08-05 15:42:01 -070063status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000064 return setupSocketServer(UnixSocketAddress(path));
65}
66
Steven Moreland2372f9d2021-08-05 15:42:01 -070067status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000068 // realizing value w/ this type at compile time to avoid ubsan abort
69 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
70
71 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
72}
73
Steven Moreland2372f9d2021-08-05 15:42:01 -070074status_t RpcServer::setupInetServer(const char* address, unsigned int port,
75 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000076 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000077 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070078 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000079 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000080 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070081 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000082 continue;
83 }
84
85 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
86 sockaddr_in addr{};
87 socklen_t len = sizeof(addr);
88 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
89 int savedErrno = errno;
90 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
91 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070092 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000093 }
94 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
95 static_cast<size_t>(len), sizeof(addr));
96 unsigned int realPort = ntohs(addr.sin_port);
97 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
98 "Requesting inet server on %s but it is set up on %u.",
99 socketAddress.toString().c_str(), realPort);
100
101 if (assignedPort != nullptr) {
102 *assignedPort = realPort;
103 }
104
Steven Moreland2372f9d2021-08-05 15:42:01 -0700105 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000106 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000107 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 +0000108 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700109 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000110}
111
Steven Morelandf137de92021-04-24 01:54:26 +0000112void RpcServer::setMaxThreads(size_t threads) {
113 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700114 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000115 mMaxThreads = threads;
116}
117
118size_t RpcServer::getMaxThreads() {
119 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000120}
121
Steven Morelandbf57bce2021-07-26 15:26:12 -0700122void RpcServer::setProtocolVersion(uint32_t version) {
123 mProtocolVersion = version;
124}
125
Frederick Mayle69a0c992022-05-26 20:38:39 +0000126void RpcServer::setSupportedFileDescriptorTransportModes(
127 const std::vector<RpcSession::FileDescriptorTransportMode>& modes) {
128 mSupportedFileDescriptorTransportModes.reset();
129 for (RpcSession::FileDescriptorTransportMode mode : modes) {
130 mSupportedFileDescriptorTransportModes.set(static_cast<size_t>(mode));
131 }
132}
133
Steven Moreland5553ac42020-11-11 02:14:45 +0000134void RpcServer::setRootObject(const sp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000135 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700136 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700137 mRootObjectWeak = mRootObject = binder;
138}
139
140void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000141 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700142 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700143 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700144 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000145}
Steven Moreland51c44a92021-10-14 16:50:35 -0700146void RpcServer::setPerSessionRootObject(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000147 std::function<sp<IBinder>(const void*, size_t)>&& makeObject) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000148 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700149 mRootObject.clear();
150 mRootObjectWeak.clear();
151 mRootObjectFactory = std::move(makeObject);
152}
Steven Moreland5553ac42020-11-11 02:14:45 +0000153
154sp<IBinder> RpcServer::getRootObject() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000155 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700156 bool hasWeak = mRootObjectWeak.unsafe_get();
157 sp<IBinder> ret = mRootObjectWeak.promote();
158 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
159 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000160}
161
Yifan Hong9734cfc2021-09-13 16:14:09 -0700162std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000163 RpcMutexLockGuard _l(mLock);
Yifan Hongecf937d2021-08-11 17:29:28 -0700164 return mCtx->getCertificate(format);
165}
166
Yifan Hong326afd12021-05-19 15:24:54 -0700167static void joinRpcServer(sp<RpcServer>&& thiz) {
168 thiz->join();
169}
170
171void RpcServer::start() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000172 RpcMutexLockGuard _l(mLock);
Yifan Hong326afd12021-05-19 15:24:54 -0700173 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000174 mJoinThread =
175 std::make_unique<RpcMaybeThread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
176 rpcJoinIfSingleThreaded(*mJoinThread);
Yifan Hong326afd12021-05-19 15:24:54 -0700177}
178
Steven Moreland611d15f2021-05-01 01:28:27 +0000179void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700180
181 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000182 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700183 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
184 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
185 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700186 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700187 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000188 }
Yifan Hong1a235852021-05-13 16:07:47 -0700189
Steven Moreland2b4f3802021-05-22 01:46:27 +0000190 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000191 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000192 std::array<uint8_t, kRpcAddressSize> addr;
193 static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
Steven Moreland51c44a92021-10-14 16:50:35 -0700194
Andrei Homescu86124ca2022-04-21 22:22:48 +0000195 socklen_t addrLen = addr.size();
Steven Moreland51c44a92021-10-14 16:50:35 -0700196 unique_fd clientFd(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000197 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(addr.data()),
Steven Moreland51c44a92021-10-14 16:50:35 -0700198 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
199
Andrei Homescu86124ca2022-04-21 22:22:48 +0000200 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(sockaddr_storage)),
201 "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000202
203 if (clientFd < 0) {
204 ALOGE("Could not accept4 socket: %s", strerror(errno));
205 continue;
206 }
207 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
208
209 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000210 RpcMutexLockGuard _l(mLock);
211 RpcMaybeThread thread = RpcMaybeThread(&RpcServer::establishConnection,
212 sp<RpcServer>::fromExisting(this),
213 std::move(clientFd), addr, addrLen);
214
215 auto& threadRef = mConnectingThreads[thread.get_id()];
216 threadRef = std::move(thread);
217 rpcJoinIfSingleThreaded(threadRef);
Steven Moreland410325a2021-06-02 18:37:42 +0000218 }
Yifan Hong1a235852021-05-13 16:07:47 -0700219 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000220 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700221
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000222 if constexpr (kEnableRpcThreads) {
223 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700224 mJoinThreadRunning = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000225 } else {
226 // Multi-threaded builds clear this in shutdown(), but we need it valid
227 // so the loop above exits cleanly
228 mShutdownTrigger = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700229 }
230 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000231}
232
Yifan Hong1a235852021-05-13 16:07:47 -0700233bool RpcServer::shutdown() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000234 RpcMutexUniqueLock _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000235 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000236 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000237 return false;
238 }
Yifan Hong1a235852021-05-13 16:07:47 -0700239
240 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700241
Steven Morelanda8b44292021-06-08 01:27:53 +0000242 for (auto& [id, session] : mSessions) {
243 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700244 // server lock is a more general lock
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000245 RpcMutexLockGuard _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000246 session->mShutdownTrigger->trigger();
247 }
248
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000249 if constexpr (!kEnableRpcThreads) {
250 // In single-threaded mode we're done here, everything else that
251 // needs to happen should be at the end of RpcServer::join()
252 return true;
253 }
254
Steven Morelandee3f4662021-05-22 01:07:33 +0000255 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000256 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
257 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
258 "Connecting threads: "
259 "%zu, Sessions: %zu. Is your server deadlocked?",
260 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
261 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000262 }
Yifan Hong1a235852021-05-13 16:07:47 -0700263
Yifan Hong326afd12021-05-19 15:24:54 -0700264 // At this point, we know join() is about to exit, but the thread that calls
265 // join() may not have exited yet.
266 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
267 // otherwise ~thread() may call std::terminate(), which may crash the process.
268 // If RpcServer does not own the join thread (aka join() is called directly),
269 // then the owner of RpcServer is responsible for cleaning up that thread.
270 if (mJoinThread.get()) {
271 mJoinThread->join();
272 mJoinThread.reset();
273 }
274
Steven Moreland1c943ec2021-07-13 23:57:56 +0000275 LOG_RPC_DETAIL("Finished waiting on shutdown.");
276
Yifan Hong1a235852021-05-13 16:07:47 -0700277 mShutdownTrigger = nullptr;
278 return true;
279}
280
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281std::vector<sp<RpcSession>> RpcServer::listSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000282 RpcMutexLockGuard _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283 std::vector<sp<RpcSession>> sessions;
284 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000285 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000286 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000287 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000288 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000289}
290
Steven Morelandd539fbf2021-05-05 23:40:25 +0000291size_t RpcServer::numUninitializedSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000292 RpcMutexLockGuard _l(mLock);
Steven Morelandd539fbf2021-05-05 23:40:25 +0000293 return mConnectingThreads.size();
294}
295
Steven Moreland51c44a92021-10-14 16:50:35 -0700296void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
Andrei Homescu86124ca2022-04-21 22:22:48 +0000297 std::array<uint8_t, kRpcAddressSize> addr, size_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000298 // mShutdownTrigger can only be cleared once connection threads have joined.
299 // It must be set before this thread is started
300 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700301 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
302
303 status_t status = OK;
304
305 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700306 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700307 if (client == nullptr) {
308 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
309 status = DEAD_OBJECT;
310 // still need to cleanup before we can return
311 } else {
312 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
313 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000314
Steven Moreland659416d2021-05-11 00:47:50 +0000315 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700316 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000317 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000318 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000319 std::nullopt, /*ancillaryFds=*/nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700320 if (status != OK) {
321 ALOGE("Failed to read ID for client connecting to RPC server: %s",
322 statusToString(status).c_str());
323 // still need to cleanup before we can return
324 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000325 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700326
Steven Moreland826367f2021-09-10 14:05:31 -0700327 std::vector<uint8_t> sessionId;
328 if (status == OK) {
329 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700330 if (header.sessionIdSize == kSessionIdBytes) {
331 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000332 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000333 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000334 std::nullopt, /*ancillaryFds=*/nullptr);
Steven Morelandc5032042021-09-30 15:40:27 -0700335 if (status != OK) {
336 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
337 statusToString(status).c_str());
338 // still need to cleanup before we can return
339 }
340 } else {
341 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
342 kSessionIdBytes, header.sessionIdSize);
343 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700344 }
345 }
346 }
347
Steven Morelandbf57bce2021-07-26 15:26:12 -0700348 bool incoming = false;
349 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700350 bool requestingNewSession = false;
351
352 if (status == OK) {
353 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
354 protocolVersion = std::min(header.version,
355 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700356 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700357
358 if (requestingNewSession) {
359 RpcNewSessionResponse response{
360 .version = protocolVersion,
361 };
362
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000363 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000364 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000365 std::nullopt, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700366 if (status != OK) {
367 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
368 // still need to cleanup before we can return
369 }
370 }
371 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000372
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000373 RpcMaybeThread thisThread;
Steven Morelanda63ff932021-05-12 00:03:15 +0000374 sp<RpcSession> session;
375 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000376 RpcMutexUniqueLock _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000377
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000378 auto threadId = server->mConnectingThreads.find(rpc_this_thread::get_id());
Yifan Hongb3005502021-05-19 15:37:00 -0700379 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000380 "Must establish connection on owned thread");
381 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000382 ScopeGuard detachGuard = [&]() {
383 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000384 _l.unlock();
385 server->mShutdownCv.notify_all();
386 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000387 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000388
Steven Morelandbf57bce2021-07-26 15:26:12 -0700389 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000390 return;
391 }
392
Steven Morelandbf57bce2021-07-26 15:26:12 -0700393 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000394 if (incoming) {
395 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000396 return;
397 }
398
Steven Moreland826367f2021-09-10 14:05:31 -0700399 // Uniquely identify session at the application layer. Even if a
400 // client/server use the same certificates, if they create multiple
401 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700402 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000403 size_t tries = 0;
404 do {
405 // don't block if there is some entropy issue
406 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700407 ALOGE("Cannot find new address: %s",
408 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000409 return;
410 }
411
Andrei Homescuc24c8792022-04-19 00:24:51 +0000412 auto status = getRandomBytes(sessionId.data(), sessionId.size());
413 if (status != OK) {
414 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700415 return;
416 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000417 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000418
Andrei Homescu5e301462022-05-12 00:52:34 +0000419 session = sp<RpcSession>::make(nullptr);
Yifan Hong10423062021-10-08 16:26:32 -0700420 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700421 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700422
Frederick Mayle26b494e2022-07-08 22:09:58 +0000423 if (header.fileDescriptorTransportMode <
424 server->mSupportedFileDescriptorTransportModes.size() &&
425 server->mSupportedFileDescriptorTransportModes.test(
Frederick Mayle69a0c992022-05-26 20:38:39 +0000426 header.fileDescriptorTransportMode)) {
427 session->setFileDescriptorTransportMode(
428 static_cast<RpcSession::FileDescriptorTransportMode>(
429 header.fileDescriptorTransportMode));
430 } else {
431 ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
432 header.fileDescriptorTransportMode);
433 return;
434 }
435
Steven Moreland51c44a92021-10-14 16:50:35 -0700436 // if null, falls back to server root
437 sp<IBinder> sessionSpecificRoot;
438 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000439 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700440 if (sessionSpecificRoot == nullptr) {
441 ALOGE("Warning: server returned null from root object factory");
442 }
443 }
444
Steven Morelanda8b44292021-06-08 01:27:53 +0000445 if (!session->setForServer(server,
446 sp<RpcServer::EventListener>::fromExisting(
447 static_cast<RpcServer::EventListener*>(
448 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700449 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000450 ALOGE("Failed to attach server to session");
451 return;
452 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000453
Steven Moreland01a6bad2021-06-11 00:59:20 +0000454 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000455 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000456 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700457 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000458 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700459 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000460 return;
461 }
462 session = it->second;
463 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000464
Steven Moreland1b304292021-07-15 22:59:34 +0000465 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700466 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000467 "server state must already be initialized");
468 return;
469 }
470
Steven Moreland5802c2b2021-05-12 20:13:04 +0000471 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000472 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000473 }
474
Yifan Hong702115c2021-06-24 15:39:18 -0700475 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000476
Steven Morelanda63ff932021-05-12 00:03:15 +0000477 // avoid strong cycle
478 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000479
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000480 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000481}
482
Steven Moreland2372f9d2021-08-05 15:42:01 -0700483status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000484 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700485 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000486
Yifan Hongb675ffe2021-08-05 16:37:17 -0700487 unique_fd serverFd(TEMP_FAILURE_RETRY(
488 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000489 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 int savedErrno = errno;
491 ALOGE("Could not create socket: %s", strerror(savedErrno));
492 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000493 }
494
495 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
496 int savedErrno = errno;
497 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700498 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000499 }
500
Yifan Honge96a1f12021-07-13 16:08:28 -0700501 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
502 // the backlog is increased to a large number.
503 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
504 // to 1.
505 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000506 int savedErrno = errno;
507 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700508 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000509 }
510
Steven Moreland704fc1a2021-05-04 23:13:14 +0000511 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
512
Steven Moreland2372f9d2021-08-05 15:42:01 -0700513 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700514 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700515 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700516 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700517 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000518}
519
Steven Morelanddd67b942021-07-23 17:15:41 -0700520void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700521 const std::vector<uint8_t>& id = session->mId;
522 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
523 LOG_RPC_DETAIL("Dropping session with address %s",
524 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000525
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000526 RpcMutexLockGuard _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700527 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000528 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700529 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000530 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700531 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000532 (void)mSessions.erase(it);
533}
534
Steven Moreland19fc9f72021-06-10 03:57:30 +0000535void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000536 mShutdownCv.notify_all();
537}
538
Yifan Hong0eb5a672021-05-12 18:00:25 -0700539bool RpcServer::hasServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000540 RpcMutexLockGuard _l(mLock);
Yifan Hong0eb5a672021-05-12 18:00:25 -0700541 return mServer.ok();
542}
543
Yifan Hong00aeb762021-05-12 17:07:36 -0700544unique_fd RpcServer::releaseServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000545 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700546 return std::move(mServer);
547}
548
Steven Moreland2372f9d2021-08-05 15:42:01 -0700549status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000550 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700551 if (mServer.ok()) {
552 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700554 }
555 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700556 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700557}
558
Steven Moreland5553ac42020-11-11 02:14:45 +0000559} // namespace android