blob: fedc1d9593abdd2863bd16346de56cfd47cbde08 [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"
David Brazdil21c887c2022-09-23 12:25:18 +010040#include "RpcTransportUtils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000041#include "RpcWireFormat.h"
Andrei Homescuc24c8792022-04-19 00:24:51 +000042#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000043
44namespace android {
45
Steven Morelandc5032042021-09-30 15:40:27 -070046constexpr size_t kSessionIdBytes = 32;
47
Steven Moreland5802c2b2021-05-12 20:13:04 +000048using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000049using base::unique_fd;
50
Yifan Hongecf937d2021-08-11 17:29:28 -070051RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070052RpcServer::~RpcServer() {
53 (void)shutdown();
54}
Steven Moreland5553ac42020-11-11 02:14:45 +000055
Yifan Hong702115c2021-06-24 15:39:18 -070056sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
57 // Default is without TLS.
58 if (rpcTransportCtxFactory == nullptr)
Andrei Homescu024727b2022-08-24 23:54:59 +000059 rpcTransportCtxFactory = makeDefaultRpcTransportCtxFactory();
Yifan Hongecf937d2021-08-11 17:29:28 -070060 auto ctx = rpcTransportCtxFactory->newServerCtx();
61 if (ctx == nullptr) return nullptr;
62 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000063}
64
David Brazdil21c887c2022-09-23 12:25:18 +010065status_t RpcServer::setupUnixDomainSocketBootstrapServer(unique_fd bootstrapFd) {
66 return setupExternalServer(std::move(bootstrapFd), &RpcServer::recvmsgSocketConnection);
67}
68
Steven Moreland2372f9d2021-08-05 15:42:01 -070069status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000070 return setupSocketServer(UnixSocketAddress(path));
71}
72
David Brazdila47dfda2022-11-22 22:52:19 +000073status_t RpcServer::setupVsockServer(unsigned int bindCid, unsigned int port) {
74 return setupSocketServer(VsockSocketAddress(bindCid, port));
Steven Moreland611d15f2021-05-01 01:28:27 +000075}
76
Steven Moreland2372f9d2021-08-05 15:42:01 -070077status_t RpcServer::setupInetServer(const char* address, unsigned int port,
78 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000079 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000080 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070081 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000082 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000083 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070084 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000085 continue;
86 }
87
88 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
89 sockaddr_in addr{};
90 socklen_t len = sizeof(addr);
Pawan49d74cb2022-08-03 21:19:11 +000091 if (0 != getsockname(mServer.fd.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
Steven Moreland611d15f2021-05-01 01:28:27 +000092 int savedErrno = errno;
93 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
94 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070095 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000096 }
97 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
98 static_cast<size_t>(len), sizeof(addr));
99 unsigned int realPort = ntohs(addr.sin_port);
100 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
101 "Requesting inet server on %s but it is set up on %u.",
102 socketAddress.toString().c_str(), realPort);
103
104 if (assignedPort != nullptr) {
105 *assignedPort = realPort;
106 }
107
Steven Moreland2372f9d2021-08-05 15:42:01 -0700108 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000109 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000110 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 +0000111 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700112 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000113}
114
Steven Morelandf137de92021-04-24 01:54:26 +0000115void RpcServer::setMaxThreads(size_t threads) {
116 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700117 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000118 mMaxThreads = threads;
119}
120
121size_t RpcServer::getMaxThreads() {
122 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000123}
124
Steven Morelandbf57bce2021-07-26 15:26:12 -0700125void RpcServer::setProtocolVersion(uint32_t version) {
126 mProtocolVersion = version;
127}
128
Frederick Mayle69a0c992022-05-26 20:38:39 +0000129void RpcServer::setSupportedFileDescriptorTransportModes(
130 const std::vector<RpcSession::FileDescriptorTransportMode>& modes) {
131 mSupportedFileDescriptorTransportModes.reset();
132 for (RpcSession::FileDescriptorTransportMode mode : modes) {
133 mSupportedFileDescriptorTransportModes.set(static_cast<size_t>(mode));
134 }
135}
136
Steven Moreland5553ac42020-11-11 02:14:45 +0000137void RpcServer::setRootObject(const sp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000138 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700139 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700140 mRootObjectWeak = mRootObject = binder;
141}
142
143void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000144 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700145 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700146 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700147 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148}
Steven Moreland51c44a92021-10-14 16:50:35 -0700149void RpcServer::setPerSessionRootObject(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000150 std::function<sp<IBinder>(const void*, size_t)>&& makeObject) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000151 RpcMutexLockGuard _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700152 mRootObject.clear();
153 mRootObjectWeak.clear();
154 mRootObjectFactory = std::move(makeObject);
155}
Steven Moreland5553ac42020-11-11 02:14:45 +0000156
David Brazdila47dfda2022-11-22 22:52:19 +0000157void RpcServer::setConnectionFilter(std::function<bool(const void*, size_t)>&& filter) {
158 RpcMutexLockGuard _l(mLock);
159 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
160 mConnectionFilter = std::move(filter);
161}
162
Steven Moreland5553ac42020-11-11 02:14:45 +0000163sp<IBinder> RpcServer::getRootObject() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000164 RpcMutexLockGuard _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700165 bool hasWeak = mRootObjectWeak.unsafe_get();
166 sp<IBinder> ret = mRootObjectWeak.promote();
167 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
168 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000169}
170
Yifan Hong9734cfc2021-09-13 16:14:09 -0700171std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000172 RpcMutexLockGuard _l(mLock);
Yifan Hongecf937d2021-08-11 17:29:28 -0700173 return mCtx->getCertificate(format);
174}
175
Yifan Hong326afd12021-05-19 15:24:54 -0700176static void joinRpcServer(sp<RpcServer>&& thiz) {
177 thiz->join();
178}
179
180void RpcServer::start() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000181 RpcMutexLockGuard _l(mLock);
Yifan Hong326afd12021-05-19 15:24:54 -0700182 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000183 mJoinThread =
184 std::make_unique<RpcMaybeThread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
185 rpcJoinIfSingleThreaded(*mJoinThread);
Yifan Hong326afd12021-05-19 15:24:54 -0700186}
187
David Brazdil21c887c2022-09-23 12:25:18 +0100188status_t RpcServer::acceptSocketConnection(const RpcServer& server, RpcTransportFd* out) {
189 RpcTransportFd clientSocket(unique_fd(TEMP_FAILURE_RETRY(
190 accept4(server.mServer.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK))));
191 if (clientSocket.fd < 0) {
192 int savedErrno = errno;
193 ALOGE("Could not accept4 socket: %s", strerror(savedErrno));
194 return -savedErrno;
195 }
196
197 *out = std::move(clientSocket);
198 return OK;
199}
200
201status_t RpcServer::recvmsgSocketConnection(const RpcServer& server, RpcTransportFd* out) {
202 int zero = 0;
203 iovec iov{&zero, sizeof(zero)};
204 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
205
206 if (receiveMessageFromSocket(server.mServer, &iov, 1, &fds) < 0) {
207 int savedErrno = errno;
208 ALOGE("Failed recvmsg: %s", strerror(savedErrno));
209 return -savedErrno;
210 }
211 if (fds.size() != 1) {
212 ALOGE("Expected exactly one fd from recvmsg, got %zu", fds.size());
213 return -EINVAL;
214 }
215
216 unique_fd fd(std::move(std::get<unique_fd>(fds.back())));
217 if (auto res = setNonBlocking(fd); !res.ok()) {
218 ALOGE("Failed setNonBlocking: %s", res.error().message().c_str());
219 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
220 }
221
222 *out = RpcTransportFd(std::move(fd));
223 return OK;
224}
225
Steven Moreland611d15f2021-05-01 01:28:27 +0000226void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700227
228 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000229 RpcMutexLockGuard _l(mLock);
Pawan49d74cb2022-08-03 21:19:11 +0000230 LOG_ALWAYS_FATAL_IF(!mServer.fd.ok(), "RpcServer must be setup to join.");
David Brazdil21c887c2022-09-23 12:25:18 +0100231 LOG_ALWAYS_FATAL_IF(mAcceptFn == nullptr, "RpcServer must have an accept() function");
Yifan Hong1a235852021-05-13 16:07:47 -0700232 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
233 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700234 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700235 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000236 }
Yifan Hong1a235852021-05-13 16:07:47 -0700237
Steven Moreland2b4f3802021-05-22 01:46:27 +0000238 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000239 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000240 std::array<uint8_t, kRpcAddressSize> addr;
241 static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
Andrei Homescu86124ca2022-04-21 22:22:48 +0000242 socklen_t addrLen = addr.size();
Steven Moreland51c44a92021-10-14 16:50:35 -0700243
David Brazdil21c887c2022-09-23 12:25:18 +0100244 RpcTransportFd clientSocket;
245 if (mAcceptFn(*this, &clientSocket) != OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000246 continue;
247 }
David Brazdila47dfda2022-11-22 22:52:19 +0000248
249 LOG_RPC_DETAIL("accept on fd %d yields fd %d", mServer.fd.get(), clientSocket.fd.get());
250
David Brazdil21c887c2022-09-23 12:25:18 +0100251 if (getpeername(clientSocket.fd.get(), reinterpret_cast<sockaddr*>(addr.data()),
252 &addrLen)) {
253 ALOGE("Could not getpeername socket: %s", strerror(errno));
254 continue;
255 }
256
David Brazdila47dfda2022-11-22 22:52:19 +0000257 if (mConnectionFilter != nullptr && !mConnectionFilter(addr.data(), addrLen)) {
258 ALOGE("Dropped client connection fd %d", clientSocket.fd.get());
259 continue;
260 }
Steven Moreland410325a2021-06-02 18:37:42 +0000261
262 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000263 RpcMutexLockGuard _l(mLock);
Andrei Homescu74a54452021-12-10 05:30:21 +0000264 RpcMaybeThread thread =
265 RpcMaybeThread(&RpcServer::establishConnection,
Pawan49d74cb2022-08-03 21:19:11 +0000266 sp<RpcServer>::fromExisting(this), std::move(clientSocket), addr,
Andrei Homescu74a54452021-12-10 05:30:21 +0000267 addrLen, RpcSession::join);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000268
269 auto& threadRef = mConnectingThreads[thread.get_id()];
270 threadRef = std::move(thread);
271 rpcJoinIfSingleThreaded(threadRef);
Steven Moreland410325a2021-06-02 18:37:42 +0000272 }
Yifan Hong1a235852021-05-13 16:07:47 -0700273 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000274 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700275
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000276 if constexpr (kEnableRpcThreads) {
277 RpcMutexLockGuard _l(mLock);
Yifan Hong1a235852021-05-13 16:07:47 -0700278 mJoinThreadRunning = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000279 } else {
280 // Multi-threaded builds clear this in shutdown(), but we need it valid
281 // so the loop above exits cleanly
282 mShutdownTrigger = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700283 }
284 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000285}
286
Yifan Hong1a235852021-05-13 16:07:47 -0700287bool RpcServer::shutdown() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000288 RpcMutexUniqueLock _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000289 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000290 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000291 return false;
292 }
Yifan Hong1a235852021-05-13 16:07:47 -0700293
294 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700295
Steven Morelanda8b44292021-06-08 01:27:53 +0000296 for (auto& [id, session] : mSessions) {
297 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700298 // server lock is a more general lock
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000299 RpcMutexLockGuard _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000300 session->mShutdownTrigger->trigger();
301 }
302
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000303 if constexpr (!kEnableRpcThreads) {
304 // In single-threaded mode we're done here, everything else that
305 // needs to happen should be at the end of RpcServer::join()
306 return true;
307 }
308
Steven Morelandee3f4662021-05-22 01:07:33 +0000309 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000310 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
311 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
312 "Connecting threads: "
313 "%zu, Sessions: %zu. Is your server deadlocked?",
314 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
315 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000316 }
Yifan Hong1a235852021-05-13 16:07:47 -0700317
Yifan Hong326afd12021-05-19 15:24:54 -0700318 // At this point, we know join() is about to exit, but the thread that calls
319 // join() may not have exited yet.
320 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
321 // otherwise ~thread() may call std::terminate(), which may crash the process.
322 // If RpcServer does not own the join thread (aka join() is called directly),
323 // then the owner of RpcServer is responsible for cleaning up that thread.
324 if (mJoinThread.get()) {
325 mJoinThread->join();
326 mJoinThread.reset();
327 }
328
Steven Moreland1c943ec2021-07-13 23:57:56 +0000329 LOG_RPC_DETAIL("Finished waiting on shutdown.");
330
Yifan Hong1a235852021-05-13 16:07:47 -0700331 mShutdownTrigger = nullptr;
332 return true;
333}
334
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335std::vector<sp<RpcSession>> RpcServer::listSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000336 RpcMutexLockGuard _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000337 std::vector<sp<RpcSession>> sessions;
338 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000339 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000340 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000341 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000343}
344
Steven Morelandd539fbf2021-05-05 23:40:25 +0000345size_t RpcServer::numUninitializedSessions() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000346 RpcMutexLockGuard _l(mLock);
Steven Morelandd539fbf2021-05-05 23:40:25 +0000347 return mConnectingThreads.size();
348}
349
Andrei Homescu74a54452021-12-10 05:30:21 +0000350void RpcServer::establishConnection(
Pawan3e0061c2022-08-26 21:08:34 +0000351 sp<RpcServer>&& server, RpcTransportFd clientFd, std::array<uint8_t, kRpcAddressSize> addr,
Andrei Homescu74a54452021-12-10 05:30:21 +0000352 size_t addrLen,
353 std::function<void(sp<RpcSession>&&, RpcSession::PreJoinSetupResult&&)>&& joinFn) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000354 // mShutdownTrigger can only be cleared once connection threads have joined.
355 // It must be set before this thread is started
356 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700357 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
358
359 status_t status = OK;
360
Pawan49d74cb2022-08-03 21:19:11 +0000361 int clientFdForLog = clientFd.fd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700362 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700363 if (client == nullptr) {
364 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
365 status = DEAD_OBJECT;
366 // still need to cleanup before we can return
367 } else {
368 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
369 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000370
Steven Moreland659416d2021-05-11 00:47:50 +0000371 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700372 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000373 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000374 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000375 std::nullopt, /*ancillaryFds=*/nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700376 if (status != OK) {
377 ALOGE("Failed to read ID for client connecting to RPC server: %s",
378 statusToString(status).c_str());
379 // still need to cleanup before we can return
380 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000381 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700382
Steven Moreland826367f2021-09-10 14:05:31 -0700383 std::vector<uint8_t> sessionId;
384 if (status == OK) {
385 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700386 if (header.sessionIdSize == kSessionIdBytes) {
387 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000388 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000389 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000390 std::nullopt, /*ancillaryFds=*/nullptr);
Steven Morelandc5032042021-09-30 15:40:27 -0700391 if (status != OK) {
392 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
393 statusToString(status).c_str());
394 // still need to cleanup before we can return
395 }
396 } else {
397 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
398 kSessionIdBytes, header.sessionIdSize);
399 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700400 }
401 }
402 }
403
Steven Morelandbf57bce2021-07-26 15:26:12 -0700404 bool incoming = false;
405 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700406 bool requestingNewSession = false;
407
408 if (status == OK) {
409 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
410 protocolVersion = std::min(header.version,
411 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700412 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700413
414 if (requestingNewSession) {
415 RpcNewSessionResponse response{
416 .version = protocolVersion,
417 };
418
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000419 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000420 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000421 std::nullopt, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700422 if (status != OK) {
423 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
424 // still need to cleanup before we can return
425 }
426 }
427 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000428
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000429 RpcMaybeThread thisThread;
Steven Morelanda63ff932021-05-12 00:03:15 +0000430 sp<RpcSession> session;
431 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000432 RpcMutexUniqueLock _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000433
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000434 auto threadId = server->mConnectingThreads.find(rpc_this_thread::get_id());
Yifan Hongb3005502021-05-19 15:37:00 -0700435 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000436 "Must establish connection on owned thread");
437 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000438 ScopeGuard detachGuard = [&]() {
439 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000440 _l.unlock();
441 server->mShutdownCv.notify_all();
442 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000443 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000444
Steven Morelandbf57bce2021-07-26 15:26:12 -0700445 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000446 return;
447 }
448
Steven Morelandbf57bce2021-07-26 15:26:12 -0700449 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000450 if (incoming) {
451 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000452 return;
453 }
454
Steven Moreland826367f2021-09-10 14:05:31 -0700455 // Uniquely identify session at the application layer. Even if a
456 // client/server use the same certificates, if they create multiple
457 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700458 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000459 size_t tries = 0;
460 do {
461 // don't block if there is some entropy issue
462 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700463 ALOGE("Cannot find new address: %s",
464 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000465 return;
466 }
467
Andrei Homescuc24c8792022-04-19 00:24:51 +0000468 auto status = getRandomBytes(sessionId.data(), sessionId.size());
469 if (status != OK) {
470 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700471 return;
472 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000473 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000474
Andrei Homescu5e301462022-05-12 00:52:34 +0000475 session = sp<RpcSession>::make(nullptr);
Yifan Hong10423062021-10-08 16:26:32 -0700476 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700477 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700478
Frederick Mayle26b494e2022-07-08 22:09:58 +0000479 if (header.fileDescriptorTransportMode <
480 server->mSupportedFileDescriptorTransportModes.size() &&
481 server->mSupportedFileDescriptorTransportModes.test(
Frederick Mayle69a0c992022-05-26 20:38:39 +0000482 header.fileDescriptorTransportMode)) {
483 session->setFileDescriptorTransportMode(
484 static_cast<RpcSession::FileDescriptorTransportMode>(
485 header.fileDescriptorTransportMode));
486 } else {
487 ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
488 header.fileDescriptorTransportMode);
489 return;
490 }
491
Steven Moreland51c44a92021-10-14 16:50:35 -0700492 // if null, falls back to server root
493 sp<IBinder> sessionSpecificRoot;
494 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000495 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700496 if (sessionSpecificRoot == nullptr) {
497 ALOGE("Warning: server returned null from root object factory");
498 }
499 }
500
Steven Morelanda8b44292021-06-08 01:27:53 +0000501 if (!session->setForServer(server,
502 sp<RpcServer::EventListener>::fromExisting(
503 static_cast<RpcServer::EventListener*>(
504 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700505 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000506 ALOGE("Failed to attach server to session");
507 return;
508 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000509
Steven Moreland01a6bad2021-06-11 00:59:20 +0000510 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000511 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000512 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700513 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000514 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700515 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000516 return;
517 }
518 session = it->second;
519 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000520
Steven Moreland1b304292021-07-15 22:59:34 +0000521 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700522 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000523 "server state must already be initialized");
524 return;
525 }
526
Steven Moreland5802c2b2021-05-12 20:13:04 +0000527 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000528 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000529 }
530
Yifan Hong702115c2021-06-24 15:39:18 -0700531 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000532
Steven Morelanda63ff932021-05-12 00:03:15 +0000533 // avoid strong cycle
534 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000535
Andrei Homescu74a54452021-12-10 05:30:21 +0000536 joinFn(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000537}
538
Steven Moreland2372f9d2021-08-05 15:42:01 -0700539status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000540 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700541 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000542
Alice Wang0b138ed2022-11-15 16:22:44 +0000543 unique_fd socket_fd(TEMP_FAILURE_RETRY(
544 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
545 if (!socket_fd.ok()) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 int savedErrno = errno;
547 ALOGE("Could not create socket: %s", strerror(savedErrno));
548 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000549 }
Alice Wang0b138ed2022-11-15 16:22:44 +0000550 if (0 != TEMP_FAILURE_RETRY(bind(socket_fd.get(), addr.addr(), addr.addrSize()))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000551 int savedErrno = errno;
552 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000554 }
555
Alice Wang0b138ed2022-11-15 16:22:44 +0000556 return setupRawSocketServer(std::move(socket_fd));
Steven Moreland611d15f2021-05-01 01:28:27 +0000557}
558
Alice Wang0b138ed2022-11-15 16:22:44 +0000559status_t RpcServer::setupRawSocketServer(unique_fd socket_fd) {
Alice Wang30c204d2022-11-15 12:50:51 +0000560 LOG_ALWAYS_FATAL_IF(!socket_fd.ok(), "Socket must be setup to listen.");
Alice Wang30c204d2022-11-15 12:50:51 +0000561
Alice Wang893a9912022-10-24 10:44:09 +0000562 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
563 // the backlog is increased to a large number.
564 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
565 // to 1.
Alice Wangdf741782022-11-16 08:37:04 +0000566 if (0 != TEMP_FAILURE_RETRY(listen(socket_fd.get(), 50 /*backlog*/))) {
Alice Wang893a9912022-10-24 10:44:09 +0000567 int savedErrno = errno;
568 ALOGE("Could not listen initialized Unix socket: %s", strerror(savedErrno));
569 return -savedErrno;
570 }
Alice Wangdf741782022-11-16 08:37:04 +0000571 if (status_t status = setupExternalServer(std::move(socket_fd)); status != OK) {
Alice Wang893a9912022-10-24 10:44:09 +0000572 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
573 return status;
574 }
575 return OK;
576}
577
Steven Morelanddd67b942021-07-23 17:15:41 -0700578void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700579 const std::vector<uint8_t>& id = session->mId;
580 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
581 LOG_RPC_DETAIL("Dropping session with address %s",
582 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000583
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000584 RpcMutexLockGuard _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700585 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000586 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700587 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000588 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700589 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000590 (void)mSessions.erase(it);
591}
592
Steven Moreland19fc9f72021-06-10 03:57:30 +0000593void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000594 mShutdownCv.notify_all();
595}
596
Yifan Hong0eb5a672021-05-12 18:00:25 -0700597bool RpcServer::hasServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000598 RpcMutexLockGuard _l(mLock);
Pawan49d74cb2022-08-03 21:19:11 +0000599 return mServer.fd.ok();
Yifan Hong0eb5a672021-05-12 18:00:25 -0700600}
601
Yifan Hong00aeb762021-05-12 17:07:36 -0700602unique_fd RpcServer::releaseServer() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000603 RpcMutexLockGuard _l(mLock);
Pawan49d74cb2022-08-03 21:19:11 +0000604 return std::move(mServer.fd);
Yifan Hong00aeb762021-05-12 17:07:36 -0700605}
606
David Brazdil21c887c2022-09-23 12:25:18 +0100607status_t RpcServer::setupExternalServer(
608 base::unique_fd serverFd,
609 std::function<status_t(const RpcServer&, RpcTransportFd*)>&& acceptFn) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000610 RpcMutexLockGuard _l(mLock);
Pawan49d74cb2022-08-03 21:19:11 +0000611 if (mServer.fd.ok()) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700612 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700613 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700614 }
615 mServer = std::move(serverFd);
David Brazdil21c887c2022-09-23 12:25:18 +0100616 mAcceptFn = std::move(acceptFn);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700617 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700618}
619
David Brazdil21c887c2022-09-23 12:25:18 +0100620status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
621 return setupExternalServer(std::move(serverFd), &RpcServer::acceptSocketConnection);
622}
623
Pawan1c24f9c2022-08-26 23:23:15 +0000624bool RpcServer::hasActiveRequests() {
625 RpcMutexLockGuard _l(mLock);
626 for (const auto& [_, session] : mSessions) {
627 if (session->hasActiveRequests()) {
628 return true;
629 }
630 }
631 return !mServer.isInPollingState();
632}
633
Steven Moreland5553ac42020-11-11 02:14:45 +0000634} // namespace android