blob: 49be4dd9eb155aa0af50a4432b8672ce75cd2ff4 [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"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000037#include "OS.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000038#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070039#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000040#include "RpcWireFormat.h"
Andrei Homescuc24c8792022-04-19 00:24:51 +000041#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000042
43namespace android {
44
Steven Morelandc5032042021-09-30 15:40:27 -070045constexpr size_t kSessionIdBytes = 32;
46
Steven Moreland5802c2b2021-05-12 20:13:04 +000047using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000048using base::unique_fd;
49
Yifan Hongecf937d2021-08-11 17:29:28 -070050RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070051RpcServer::~RpcServer() {
52 (void)shutdown();
53}
Steven Moreland5553ac42020-11-11 02:14:45 +000054
Yifan Hong702115c2021-06-24 15:39:18 -070055sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
56 // Default is without TLS.
57 if (rpcTransportCtxFactory == nullptr)
58 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070059 auto ctx = rpcTransportCtxFactory->newServerCtx();
60 if (ctx == nullptr) return nullptr;
61 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000062}
63
Steven Moreland2372f9d2021-08-05 15:42:01 -070064status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000065 return setupSocketServer(UnixSocketAddress(path));
66}
67
Steven Moreland2372f9d2021-08-05 15:42:01 -070068status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000069 // realizing value w/ this type at compile time to avoid ubsan abort
70 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
71
72 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
73}
74
Steven Moreland2372f9d2021-08-05 15:42:01 -070075status_t RpcServer::setupInetServer(const char* address, unsigned int port,
76 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000077 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000078 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070079 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000080 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000081 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070082 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000083 continue;
84 }
85
86 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
87 sockaddr_in addr{};
88 socklen_t len = sizeof(addr);
89 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
90 int savedErrno = errno;
91 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
92 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070093 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000094 }
95 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
96 static_cast<size_t>(len), sizeof(addr));
97 unsigned int realPort = ntohs(addr.sin_port);
98 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
99 "Requesting inet server on %s but it is set up on %u.",
100 socketAddress.toString().c_str(), realPort);
101
102 if (assignedPort != nullptr) {
103 *assignedPort = realPort;
104 }
105
Steven Moreland2372f9d2021-08-05 15:42:01 -0700106 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000107 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000108 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 +0000109 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700110 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000111}
112
Steven Morelandf137de92021-04-24 01:54:26 +0000113void RpcServer::setMaxThreads(size_t threads) {
114 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700115 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000116 mMaxThreads = threads;
117}
118
119size_t RpcServer::getMaxThreads() {
120 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000121}
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123void RpcServer::setProtocolVersion(uint32_t version) {
124 mProtocolVersion = version;
125}
126
Frederick Mayle69a0c992022-05-26 20:38:39 +0000127void RpcServer::setSupportedFileDescriptorTransportModes(
128 const std::vector<RpcSession::FileDescriptorTransportMode>& modes) {
129 mSupportedFileDescriptorTransportModes.reset();
130 for (RpcSession::FileDescriptorTransportMode mode : modes) {
131 mSupportedFileDescriptorTransportModes.set(static_cast<size_t>(mode));
132 }
133}
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135void RpcServer::setRootObject(const sp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000136 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700137 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700138 mRootObjectWeak = mRootObject = binder;
139}
140
141void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000142 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700143 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700144 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700145 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000146}
Steven Moreland51c44a92021-10-14 16:50:35 -0700147void RpcServer::setPerSessionRootObject(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000148 std::function<sp<IBinder>(const void*, size_t)>&& makeObject) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000149 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700150 mRootObject.clear();
151 mRootObjectWeak.clear();
152 mRootObjectFactory = std::move(makeObject);
153}
Steven Moreland5553ac42020-11-11 02:14:45 +0000154
155sp<IBinder> RpcServer::getRootObject() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000156 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700157 bool hasWeak = mRootObjectWeak.unsafe_get();
158 sp<IBinder> ret = mRootObjectWeak.promote();
159 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
160 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000161}
162
Yifan Hong9734cfc2021-09-13 16:14:09 -0700163std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000164 RpcMutexLockGuard _l(mLock);
Yifan Hongecf937d2021-08-11 17:29:28 -0700165 return mCtx->getCertificate(format);
166}
167
Yifan Hong326afd12021-05-19 15:24:54 -0700168static void joinRpcServer(sp<RpcServer>&& thiz) {
169 thiz->join();
170}
171
172void RpcServer::start() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000173 RpcMutexLockGuard _l(mLock);
Yifan Hong326afd12021-05-19 15:24:54 -0700174 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000175 mJoinThread =
176 std::make_unique<RpcMaybeThread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
177 rpcJoinIfSingleThreaded(*mJoinThread);
Yifan Hong326afd12021-05-19 15:24:54 -0700178}
179
Steven Moreland611d15f2021-05-01 01:28:27 +0000180void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700181
182 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000183 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700184 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
185 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
186 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700187 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700188 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000189 }
Yifan Hong1a235852021-05-13 16:07:47 -0700190
Steven Moreland2b4f3802021-05-22 01:46:27 +0000191 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000192 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000193 std::array<uint8_t, kRpcAddressSize> addr;
194 static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
Steven Moreland51c44a92021-10-14 16:50:35 -0700195
Andrei Homescu86124ca2022-04-21 22:22:48 +0000196 socklen_t addrLen = addr.size();
Steven Moreland51c44a92021-10-14 16:50:35 -0700197 unique_fd clientFd(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000198 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(addr.data()),
Steven Moreland51c44a92021-10-14 16:50:35 -0700199 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
200
Andrei Homescu86124ca2022-04-21 22:22:48 +0000201 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(sockaddr_storage)),
202 "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000203
204 if (clientFd < 0) {
205 ALOGE("Could not accept4 socket: %s", strerror(errno));
206 continue;
207 }
208 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
209
210 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000211 RpcMutexLockGuard _l(mLock);
Andrei Homescu74a54452021-12-10 05:30:21 +0000212 RpcMaybeThread thread =
213 RpcMaybeThread(&RpcServer::establishConnection,
214 sp<RpcServer>::fromExisting(this), std::move(clientFd), addr,
215 addrLen, RpcSession::join);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000216
217 auto& threadRef = mConnectingThreads[thread.get_id()];
218 threadRef = std::move(thread);
219 rpcJoinIfSingleThreaded(threadRef);
Steven Moreland410325a2021-06-02 18:37:42 +0000220 }
Yifan Hong1a235852021-05-13 16:07:47 -0700221 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000222 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700223
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000224 if constexpr (kEnableRpcThreads) {
225 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700226 mJoinThreadRunning = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000227 } else {
228 // Multi-threaded builds clear this in shutdown(), but we need it valid
229 // so the loop above exits cleanly
230 mShutdownTrigger = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700231 }
232 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000233}
234
Yifan Hong1a235852021-05-13 16:07:47 -0700235bool RpcServer::shutdown() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000236 RpcMutexUniqueLock _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000237 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000238 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000239 return false;
240 }
Yifan Hong1a235852021-05-13 16:07:47 -0700241
242 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700243
Steven Morelanda8b44292021-06-08 01:27:53 +0000244 for (auto& [id, session] : mSessions) {
245 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700246 // server lock is a more general lock
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000247 RpcMutexLockGuard _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000248 session->mShutdownTrigger->trigger();
249 }
250
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000251 if constexpr (!kEnableRpcThreads) {
252 // In single-threaded mode we're done here, everything else that
253 // needs to happen should be at the end of RpcServer::join()
254 return true;
255 }
256
Steven Morelandee3f4662021-05-22 01:07:33 +0000257 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000258 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
259 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
260 "Connecting threads: "
261 "%zu, Sessions: %zu. Is your server deadlocked?",
262 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
263 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000264 }
Yifan Hong1a235852021-05-13 16:07:47 -0700265
Yifan Hong326afd12021-05-19 15:24:54 -0700266 // At this point, we know join() is about to exit, but the thread that calls
267 // join() may not have exited yet.
268 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
269 // otherwise ~thread() may call std::terminate(), which may crash the process.
270 // If RpcServer does not own the join thread (aka join() is called directly),
271 // then the owner of RpcServer is responsible for cleaning up that thread.
272 if (mJoinThread.get()) {
273 mJoinThread->join();
274 mJoinThread.reset();
275 }
276
Steven Moreland1c943ec2021-07-13 23:57:56 +0000277 LOG_RPC_DETAIL("Finished waiting on shutdown.");
278
Yifan Hong1a235852021-05-13 16:07:47 -0700279 mShutdownTrigger = nullptr;
280 return true;
281}
282
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283std::vector<sp<RpcSession>> RpcServer::listSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000284 RpcMutexLockGuard _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 std::vector<sp<RpcSession>> sessions;
286 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000287 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000288 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000289 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000291}
292
Steven Morelandd539fbf2021-05-05 23:40:25 +0000293size_t RpcServer::numUninitializedSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000294 RpcMutexLockGuard _l(mLock);
Steven Morelandd539fbf2021-05-05 23:40:25 +0000295 return mConnectingThreads.size();
296}
297
Andrei Homescu74a54452021-12-10 05:30:21 +0000298void RpcServer::establishConnection(
299 sp<RpcServer>&& server, base::unique_fd clientFd, std::array<uint8_t, kRpcAddressSize> addr,
300 size_t addrLen,
301 std::function<void(sp<RpcSession>&&, RpcSession::PreJoinSetupResult&&)>&& joinFn) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000302 // mShutdownTrigger can only be cleared once connection threads have joined.
303 // It must be set before this thread is started
304 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700305 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
306
307 status_t status = OK;
308
309 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700310 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700311 if (client == nullptr) {
312 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
313 status = DEAD_OBJECT;
314 // still need to cleanup before we can return
315 } else {
316 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
317 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000318
Steven Moreland659416d2021-05-11 00:47:50 +0000319 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700320 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000321 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000322 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000323 std::nullopt, /*ancillaryFds=*/nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700324 if (status != OK) {
325 ALOGE("Failed to read ID for client connecting to RPC server: %s",
326 statusToString(status).c_str());
327 // still need to cleanup before we can return
328 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000329 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700330
Steven Moreland826367f2021-09-10 14:05:31 -0700331 std::vector<uint8_t> sessionId;
332 if (status == OK) {
333 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700334 if (header.sessionIdSize == kSessionIdBytes) {
335 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000336 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000337 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000338 std::nullopt, /*ancillaryFds=*/nullptr);
Steven Morelandc5032042021-09-30 15:40:27 -0700339 if (status != OK) {
340 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
341 statusToString(status).c_str());
342 // still need to cleanup before we can return
343 }
344 } else {
345 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
346 kSessionIdBytes, header.sessionIdSize);
347 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700348 }
349 }
350 }
351
Steven Morelandbf57bce2021-07-26 15:26:12 -0700352 bool incoming = false;
353 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700354 bool requestingNewSession = false;
355
356 if (status == OK) {
357 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
358 protocolVersion = std::min(header.version,
359 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700360 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700361
362 if (requestingNewSession) {
363 RpcNewSessionResponse response{
364 .version = protocolVersion,
365 };
366
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000367 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000368 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000369 std::nullopt, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700370 if (status != OK) {
371 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
372 // still need to cleanup before we can return
373 }
374 }
375 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000376
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000377 RpcMaybeThread thisThread;
Steven Morelanda63ff932021-05-12 00:03:15 +0000378 sp<RpcSession> session;
379 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000380 RpcMutexUniqueLock _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000381
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000382 auto threadId = server->mConnectingThreads.find(rpc_this_thread::get_id());
Yifan Hongb3005502021-05-19 15:37:00 -0700383 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000384 "Must establish connection on owned thread");
385 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000386 ScopeGuard detachGuard = [&]() {
387 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000388 _l.unlock();
389 server->mShutdownCv.notify_all();
390 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000391 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000392
Steven Morelandbf57bce2021-07-26 15:26:12 -0700393 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000394 return;
395 }
396
Steven Morelandbf57bce2021-07-26 15:26:12 -0700397 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000398 if (incoming) {
399 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000400 return;
401 }
402
Steven Moreland826367f2021-09-10 14:05:31 -0700403 // Uniquely identify session at the application layer. Even if a
404 // client/server use the same certificates, if they create multiple
405 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700406 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000407 size_t tries = 0;
408 do {
409 // don't block if there is some entropy issue
410 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700411 ALOGE("Cannot find new address: %s",
412 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000413 return;
414 }
415
Andrei Homescuc24c8792022-04-19 00:24:51 +0000416 auto status = getRandomBytes(sessionId.data(), sessionId.size());
417 if (status != OK) {
418 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700419 return;
420 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000421 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000422
Andrei Homescu5e301462022-05-12 00:52:34 +0000423 session = sp<RpcSession>::make(nullptr);
Yifan Hong10423062021-10-08 16:26:32 -0700424 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700425 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700426
Frederick Mayle26b494e2022-07-08 22:09:58 +0000427 if (header.fileDescriptorTransportMode <
428 server->mSupportedFileDescriptorTransportModes.size() &&
429 server->mSupportedFileDescriptorTransportModes.test(
Frederick Mayle69a0c992022-05-26 20:38:39 +0000430 header.fileDescriptorTransportMode)) {
431 session->setFileDescriptorTransportMode(
432 static_cast<RpcSession::FileDescriptorTransportMode>(
433 header.fileDescriptorTransportMode));
434 } else {
435 ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
436 header.fileDescriptorTransportMode);
437 return;
438 }
439
Steven Moreland51c44a92021-10-14 16:50:35 -0700440 // if null, falls back to server root
441 sp<IBinder> sessionSpecificRoot;
442 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000443 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700444 if (sessionSpecificRoot == nullptr) {
445 ALOGE("Warning: server returned null from root object factory");
446 }
447 }
448
Steven Morelanda8b44292021-06-08 01:27:53 +0000449 if (!session->setForServer(server,
450 sp<RpcServer::EventListener>::fromExisting(
451 static_cast<RpcServer::EventListener*>(
452 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700453 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000454 ALOGE("Failed to attach server to session");
455 return;
456 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000457
Steven Moreland01a6bad2021-06-11 00:59:20 +0000458 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000459 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000460 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700461 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000462 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700463 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000464 return;
465 }
466 session = it->second;
467 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000468
Steven Moreland1b304292021-07-15 22:59:34 +0000469 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700470 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000471 "server state must already be initialized");
472 return;
473 }
474
Steven Moreland5802c2b2021-05-12 20:13:04 +0000475 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000476 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000477 }
478
Yifan Hong702115c2021-06-24 15:39:18 -0700479 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000480
Steven Morelanda63ff932021-05-12 00:03:15 +0000481 // avoid strong cycle
482 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000483
Andrei Homescu74a54452021-12-10 05:30:21 +0000484 joinFn(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000485}
486
Steven Moreland2372f9d2021-08-05 15:42:01 -0700487status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000488 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700489 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000490
Yifan Hongb675ffe2021-08-05 16:37:17 -0700491 unique_fd serverFd(TEMP_FAILURE_RETRY(
492 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000493 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700494 int savedErrno = errno;
495 ALOGE("Could not create socket: %s", strerror(savedErrno));
496 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000497 }
498
499 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
500 int savedErrno = errno;
501 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700502 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000503 }
504
Yifan Honge96a1f12021-07-13 16:08:28 -0700505 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
506 // the backlog is increased to a large number.
507 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
508 // to 1.
509 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000510 int savedErrno = errno;
511 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700512 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000513 }
514
Steven Moreland704fc1a2021-05-04 23:13:14 +0000515 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
516
Steven Moreland2372f9d2021-08-05 15:42:01 -0700517 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700518 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700519 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700520 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700521 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000522}
523
Steven Morelanddd67b942021-07-23 17:15:41 -0700524void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700525 const std::vector<uint8_t>& id = session->mId;
526 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
527 LOG_RPC_DETAIL("Dropping session with address %s",
528 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000529
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000530 RpcMutexLockGuard _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700531 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000532 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700533 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000534 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700535 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000536 (void)mSessions.erase(it);
537}
538
Steven Moreland19fc9f72021-06-10 03:57:30 +0000539void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000540 mShutdownCv.notify_all();
541}
542
Yifan Hong0eb5a672021-05-12 18:00:25 -0700543bool RpcServer::hasServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000544 RpcMutexLockGuard _l(mLock);
Yifan Hong0eb5a672021-05-12 18:00:25 -0700545 return mServer.ok();
546}
547
Yifan Hong00aeb762021-05-12 17:07:36 -0700548unique_fd RpcServer::releaseServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000549 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700550 return std::move(mServer);
551}
552
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000554 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700555 if (mServer.ok()) {
556 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700558 }
559 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700560 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700561}
562
Steven Moreland5553ac42020-11-11 02:14:45 +0000563} // namespace android