blob: 096d5cc5ad0180385854d63428b75a718c76ae99 [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);
212 RpcMaybeThread thread = RpcMaybeThread(&RpcServer::establishConnection,
213 sp<RpcServer>::fromExisting(this),
214 std::move(clientFd), addr, addrLen);
215
216 auto& threadRef = mConnectingThreads[thread.get_id()];
217 threadRef = std::move(thread);
218 rpcJoinIfSingleThreaded(threadRef);
Steven Moreland410325a2021-06-02 18:37:42 +0000219 }
Yifan Hong1a235852021-05-13 16:07:47 -0700220 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000221 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700222
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000223 if constexpr (kEnableRpcThreads) {
224 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700225 mJoinThreadRunning = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000226 } else {
227 // Multi-threaded builds clear this in shutdown(), but we need it valid
228 // so the loop above exits cleanly
229 mShutdownTrigger = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700230 }
231 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000232}
233
Yifan Hong1a235852021-05-13 16:07:47 -0700234bool RpcServer::shutdown() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000235 RpcMutexUniqueLock _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000236 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000237 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000238 return false;
239 }
Yifan Hong1a235852021-05-13 16:07:47 -0700240
241 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700242
Steven Morelanda8b44292021-06-08 01:27:53 +0000243 for (auto& [id, session] : mSessions) {
244 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700245 // server lock is a more general lock
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000246 RpcMutexLockGuard _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000247 session->mShutdownTrigger->trigger();
248 }
249
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000250 if constexpr (!kEnableRpcThreads) {
251 // In single-threaded mode we're done here, everything else that
252 // needs to happen should be at the end of RpcServer::join()
253 return true;
254 }
255
Steven Morelandee3f4662021-05-22 01:07:33 +0000256 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000257 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
258 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
259 "Connecting threads: "
260 "%zu, Sessions: %zu. Is your server deadlocked?",
261 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
262 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000263 }
Yifan Hong1a235852021-05-13 16:07:47 -0700264
Yifan Hong326afd12021-05-19 15:24:54 -0700265 // At this point, we know join() is about to exit, but the thread that calls
266 // join() may not have exited yet.
267 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
268 // otherwise ~thread() may call std::terminate(), which may crash the process.
269 // If RpcServer does not own the join thread (aka join() is called directly),
270 // then the owner of RpcServer is responsible for cleaning up that thread.
271 if (mJoinThread.get()) {
272 mJoinThread->join();
273 mJoinThread.reset();
274 }
275
Steven Moreland1c943ec2021-07-13 23:57:56 +0000276 LOG_RPC_DETAIL("Finished waiting on shutdown.");
277
Yifan Hong1a235852021-05-13 16:07:47 -0700278 mShutdownTrigger = nullptr;
279 return true;
280}
281
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282std::vector<sp<RpcSession>> RpcServer::listSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000283 RpcMutexLockGuard _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284 std::vector<sp<RpcSession>> sessions;
285 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000286 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000288 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000290}
291
Steven Morelandd539fbf2021-05-05 23:40:25 +0000292size_t RpcServer::numUninitializedSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000293 RpcMutexLockGuard _l(mLock);
Steven Morelandd539fbf2021-05-05 23:40:25 +0000294 return mConnectingThreads.size();
295}
296
Steven Moreland51c44a92021-10-14 16:50:35 -0700297void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
Andrei Homescu86124ca2022-04-21 22:22:48 +0000298 std::array<uint8_t, kRpcAddressSize> addr, size_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000299 // mShutdownTrigger can only be cleared once connection threads have joined.
300 // It must be set before this thread is started
301 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700302 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
303
304 status_t status = OK;
305
306 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700307 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700308 if (client == nullptr) {
309 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
310 status = DEAD_OBJECT;
311 // still need to cleanup before we can return
312 } else {
313 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
314 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000315
Steven Moreland659416d2021-05-11 00:47:50 +0000316 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700317 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000318 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000319 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000320 std::nullopt, /*ancillaryFds=*/nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700321 if (status != OK) {
322 ALOGE("Failed to read ID for client connecting to RPC server: %s",
323 statusToString(status).c_str());
324 // still need to cleanup before we can return
325 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000326 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700327
Steven Moreland826367f2021-09-10 14:05:31 -0700328 std::vector<uint8_t> sessionId;
329 if (status == OK) {
330 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700331 if (header.sessionIdSize == kSessionIdBytes) {
332 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000333 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000334 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000335 std::nullopt, /*ancillaryFds=*/nullptr);
Steven Morelandc5032042021-09-30 15:40:27 -0700336 if (status != OK) {
337 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
338 statusToString(status).c_str());
339 // still need to cleanup before we can return
340 }
341 } else {
342 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
343 kSessionIdBytes, header.sessionIdSize);
344 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700345 }
346 }
347 }
348
Steven Morelandbf57bce2021-07-26 15:26:12 -0700349 bool incoming = false;
350 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700351 bool requestingNewSession = false;
352
353 if (status == OK) {
354 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
355 protocolVersion = std::min(header.version,
356 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700357 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700358
359 if (requestingNewSession) {
360 RpcNewSessionResponse response{
361 .version = protocolVersion,
362 };
363
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000364 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000365 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 std::nullopt, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700367 if (status != OK) {
368 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
369 // still need to cleanup before we can return
370 }
371 }
372 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000373
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000374 RpcMaybeThread thisThread;
Steven Morelanda63ff932021-05-12 00:03:15 +0000375 sp<RpcSession> session;
376 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000377 RpcMutexUniqueLock _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000378
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000379 auto threadId = server->mConnectingThreads.find(rpc_this_thread::get_id());
Yifan Hongb3005502021-05-19 15:37:00 -0700380 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000381 "Must establish connection on owned thread");
382 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000383 ScopeGuard detachGuard = [&]() {
384 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000385 _l.unlock();
386 server->mShutdownCv.notify_all();
387 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000388 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000389
Steven Morelandbf57bce2021-07-26 15:26:12 -0700390 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000391 return;
392 }
393
Steven Morelandbf57bce2021-07-26 15:26:12 -0700394 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000395 if (incoming) {
396 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000397 return;
398 }
399
Steven Moreland826367f2021-09-10 14:05:31 -0700400 // Uniquely identify session at the application layer. Even if a
401 // client/server use the same certificates, if they create multiple
402 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700403 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000404 size_t tries = 0;
405 do {
406 // don't block if there is some entropy issue
407 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700408 ALOGE("Cannot find new address: %s",
409 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000410 return;
411 }
412
Andrei Homescuc24c8792022-04-19 00:24:51 +0000413 auto status = getRandomBytes(sessionId.data(), sessionId.size());
414 if (status != OK) {
415 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700416 return;
417 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000418 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000419
Andrei Homescu5e301462022-05-12 00:52:34 +0000420 session = sp<RpcSession>::make(nullptr);
Yifan Hong10423062021-10-08 16:26:32 -0700421 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700422 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700423
Frederick Mayle26b494e2022-07-08 22:09:58 +0000424 if (header.fileDescriptorTransportMode <
425 server->mSupportedFileDescriptorTransportModes.size() &&
426 server->mSupportedFileDescriptorTransportModes.test(
Frederick Mayle69a0c992022-05-26 20:38:39 +0000427 header.fileDescriptorTransportMode)) {
428 session->setFileDescriptorTransportMode(
429 static_cast<RpcSession::FileDescriptorTransportMode>(
430 header.fileDescriptorTransportMode));
431 } else {
432 ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
433 header.fileDescriptorTransportMode);
434 return;
435 }
436
Steven Moreland51c44a92021-10-14 16:50:35 -0700437 // if null, falls back to server root
438 sp<IBinder> sessionSpecificRoot;
439 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000440 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700441 if (sessionSpecificRoot == nullptr) {
442 ALOGE("Warning: server returned null from root object factory");
443 }
444 }
445
Steven Morelanda8b44292021-06-08 01:27:53 +0000446 if (!session->setForServer(server,
447 sp<RpcServer::EventListener>::fromExisting(
448 static_cast<RpcServer::EventListener*>(
449 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700450 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000451 ALOGE("Failed to attach server to session");
452 return;
453 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000454
Steven Moreland01a6bad2021-06-11 00:59:20 +0000455 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000456 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000457 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700458 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000459 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700460 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000461 return;
462 }
463 session = it->second;
464 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000465
Steven Moreland1b304292021-07-15 22:59:34 +0000466 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700467 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000468 "server state must already be initialized");
469 return;
470 }
471
Steven Moreland5802c2b2021-05-12 20:13:04 +0000472 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000473 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000474 }
475
Yifan Hong702115c2021-06-24 15:39:18 -0700476 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000477
Steven Morelanda63ff932021-05-12 00:03:15 +0000478 // avoid strong cycle
479 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000480
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000481 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000482}
483
Steven Moreland2372f9d2021-08-05 15:42:01 -0700484status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000485 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700486 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000487
Yifan Hongb675ffe2021-08-05 16:37:17 -0700488 unique_fd serverFd(TEMP_FAILURE_RETRY(
489 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000490 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700491 int savedErrno = errno;
492 ALOGE("Could not create socket: %s", strerror(savedErrno));
493 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000494 }
495
496 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
497 int savedErrno = errno;
498 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700499 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000500 }
501
Yifan Honge96a1f12021-07-13 16:08:28 -0700502 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
503 // the backlog is increased to a large number.
504 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
505 // to 1.
506 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000507 int savedErrno = errno;
508 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700509 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000510 }
511
Steven Moreland704fc1a2021-05-04 23:13:14 +0000512 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
513
Steven Moreland2372f9d2021-08-05 15:42:01 -0700514 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700515 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700516 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700517 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700518 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000519}
520
Steven Morelanddd67b942021-07-23 17:15:41 -0700521void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700522 const std::vector<uint8_t>& id = session->mId;
523 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
524 LOG_RPC_DETAIL("Dropping session with address %s",
525 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000526
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000527 RpcMutexLockGuard _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700528 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000529 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700530 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000531 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700532 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000533 (void)mSessions.erase(it);
534}
535
Steven Moreland19fc9f72021-06-10 03:57:30 +0000536void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000537 mShutdownCv.notify_all();
538}
539
Yifan Hong0eb5a672021-05-12 18:00:25 -0700540bool RpcServer::hasServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000541 RpcMutexLockGuard _l(mLock);
Yifan Hong0eb5a672021-05-12 18:00:25 -0700542 return mServer.ok();
543}
544
Yifan Hong00aeb762021-05-12 17:07:36 -0700545unique_fd RpcServer::releaseServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000546 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700547 return std::move(mServer);
548}
549
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000551 RpcMutexLockGuard _l(mLock);
Yifan Hong00aeb762021-05-12 17:07:36 -0700552 if (mServer.ok()) {
553 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700554 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700555 }
556 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700558}
559
Steven Moreland5553ac42020-11-11 02:14:45 +0000560} // namespace android