1*38e8c45fSAndroid Build Coastguard Worker /*
2*38e8c45fSAndroid Build Coastguard Worker * Copyright (C) 2020 The Android Open Source Project
3*38e8c45fSAndroid Build Coastguard Worker *
4*38e8c45fSAndroid Build Coastguard Worker * Licensed under the Apache License, Version 2.0 (the "License");
5*38e8c45fSAndroid Build Coastguard Worker * you may not use this file except in compliance with the License.
6*38e8c45fSAndroid Build Coastguard Worker * You may obtain a copy of the License at
7*38e8c45fSAndroid Build Coastguard Worker *
8*38e8c45fSAndroid Build Coastguard Worker * http://www.apache.org/licenses/LICENSE-2.0
9*38e8c45fSAndroid Build Coastguard Worker *
10*38e8c45fSAndroid Build Coastguard Worker * Unless required by applicable law or agreed to in writing, software
11*38e8c45fSAndroid Build Coastguard Worker * distributed under the License is distributed on an "AS IS" BASIS,
12*38e8c45fSAndroid Build Coastguard Worker * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*38e8c45fSAndroid Build Coastguard Worker * See the License for the specific language governing permissions and
14*38e8c45fSAndroid Build Coastguard Worker * limitations under the License.
15*38e8c45fSAndroid Build Coastguard Worker */
16*38e8c45fSAndroid Build Coastguard Worker
17*38e8c45fSAndroid Build Coastguard Worker #define LOG_TAG "RpcServer"
18*38e8c45fSAndroid Build Coastguard Worker
19*38e8c45fSAndroid Build Coastguard Worker #include <inttypes.h>
20*38e8c45fSAndroid Build Coastguard Worker #include <netinet/tcp.h>
21*38e8c45fSAndroid Build Coastguard Worker #include <poll.h>
22*38e8c45fSAndroid Build Coastguard Worker #include <sys/socket.h>
23*38e8c45fSAndroid Build Coastguard Worker #include <sys/un.h>
24*38e8c45fSAndroid Build Coastguard Worker
25*38e8c45fSAndroid Build Coastguard Worker #include <thread>
26*38e8c45fSAndroid Build Coastguard Worker #include <vector>
27*38e8c45fSAndroid Build Coastguard Worker
28*38e8c45fSAndroid Build Coastguard Worker #include <binder/Functional.h>
29*38e8c45fSAndroid Build Coastguard Worker #include <binder/Parcel.h>
30*38e8c45fSAndroid Build Coastguard Worker #include <binder/RpcServer.h>
31*38e8c45fSAndroid Build Coastguard Worker #include <binder/RpcTransportRaw.h>
32*38e8c45fSAndroid Build Coastguard Worker #include <log/log.h>
33*38e8c45fSAndroid Build Coastguard Worker
34*38e8c45fSAndroid Build Coastguard Worker #include "BuildFlags.h"
35*38e8c45fSAndroid Build Coastguard Worker #include "FdTrigger.h"
36*38e8c45fSAndroid Build Coastguard Worker #include "OS.h"
37*38e8c45fSAndroid Build Coastguard Worker #include "RpcSocketAddress.h"
38*38e8c45fSAndroid Build Coastguard Worker #include "RpcState.h"
39*38e8c45fSAndroid Build Coastguard Worker #include "RpcTransportUtils.h"
40*38e8c45fSAndroid Build Coastguard Worker #include "RpcWireFormat.h"
41*38e8c45fSAndroid Build Coastguard Worker #include "Utils.h"
42*38e8c45fSAndroid Build Coastguard Worker
43*38e8c45fSAndroid Build Coastguard Worker namespace android {
44*38e8c45fSAndroid Build Coastguard Worker
45*38e8c45fSAndroid Build Coastguard Worker constexpr size_t kSessionIdBytes = 32;
46*38e8c45fSAndroid Build Coastguard Worker
47*38e8c45fSAndroid Build Coastguard Worker using namespace android::binder::impl;
48*38e8c45fSAndroid Build Coastguard Worker using android::binder::borrowed_fd;
49*38e8c45fSAndroid Build Coastguard Worker using android::binder::unique_fd;
50*38e8c45fSAndroid Build Coastguard Worker
RpcServer(std::unique_ptr<RpcTransportCtx> ctx)51*38e8c45fSAndroid Build Coastguard Worker RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
~RpcServer()52*38e8c45fSAndroid Build Coastguard Worker RpcServer::~RpcServer() {
53*38e8c45fSAndroid Build Coastguard Worker RpcMutexUniqueLock _l(mLock);
54*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Must call shutdown() before destructor");
55*38e8c45fSAndroid Build Coastguard Worker }
56*38e8c45fSAndroid Build Coastguard Worker
make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)57*38e8c45fSAndroid Build Coastguard Worker sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
58*38e8c45fSAndroid Build Coastguard Worker // Default is without TLS.
59*38e8c45fSAndroid Build Coastguard Worker if (rpcTransportCtxFactory == nullptr)
60*38e8c45fSAndroid Build Coastguard Worker rpcTransportCtxFactory = binder::os::makeDefaultRpcTransportCtxFactory();
61*38e8c45fSAndroid Build Coastguard Worker auto ctx = rpcTransportCtxFactory->newServerCtx();
62*38e8c45fSAndroid Build Coastguard Worker if (ctx == nullptr) return nullptr;
63*38e8c45fSAndroid Build Coastguard Worker return sp<RpcServer>::make(std::move(ctx));
64*38e8c45fSAndroid Build Coastguard Worker }
65*38e8c45fSAndroid Build Coastguard Worker
setupUnixDomainSocketBootstrapServer(unique_fd bootstrapFd)66*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupUnixDomainSocketBootstrapServer(unique_fd bootstrapFd) {
67*38e8c45fSAndroid Build Coastguard Worker return setupExternalServer(std::move(bootstrapFd), &RpcServer::recvmsgSocketConnection);
68*38e8c45fSAndroid Build Coastguard Worker }
69*38e8c45fSAndroid Build Coastguard Worker
setupUnixDomainServer(const char * path)70*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupUnixDomainServer(const char* path) {
71*38e8c45fSAndroid Build Coastguard Worker return setupSocketServer(UnixSocketAddress(path));
72*38e8c45fSAndroid Build Coastguard Worker }
73*38e8c45fSAndroid Build Coastguard Worker
setupVsockServer(unsigned bindCid,unsigned port,unsigned * assignedPort)74*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupVsockServer(unsigned bindCid, unsigned port, unsigned* assignedPort) {
75*38e8c45fSAndroid Build Coastguard Worker auto status = setupSocketServer(VsockSocketAddress(bindCid, port));
76*38e8c45fSAndroid Build Coastguard Worker if (status != OK) return status;
77*38e8c45fSAndroid Build Coastguard Worker
78*38e8c45fSAndroid Build Coastguard Worker if (assignedPort == nullptr) return OK;
79*38e8c45fSAndroid Build Coastguard Worker sockaddr_vm addr;
80*38e8c45fSAndroid Build Coastguard Worker socklen_t len = sizeof(addr);
81*38e8c45fSAndroid Build Coastguard Worker if (0 != getsockname(mServer.fd.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
82*38e8c45fSAndroid Build Coastguard Worker status = -errno;
83*38e8c45fSAndroid Build Coastguard Worker ALOGE("setupVsockServer: Failed to getsockname: %s", strerror(-status));
84*38e8c45fSAndroid Build Coastguard Worker return status;
85*38e8c45fSAndroid Build Coastguard Worker }
86*38e8c45fSAndroid Build Coastguard Worker
87*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
88*38e8c45fSAndroid Build Coastguard Worker static_cast<size_t>(len), sizeof(addr));
89*38e8c45fSAndroid Build Coastguard Worker *assignedPort = addr.svm_port;
90*38e8c45fSAndroid Build Coastguard Worker return OK;
91*38e8c45fSAndroid Build Coastguard Worker }
92*38e8c45fSAndroid Build Coastguard Worker
setupInetServer(const char * address,unsigned int port,unsigned int * assignedPort)93*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupInetServer(const char* address, unsigned int port,
94*38e8c45fSAndroid Build Coastguard Worker unsigned int* assignedPort) {
95*38e8c45fSAndroid Build Coastguard Worker if (assignedPort != nullptr) *assignedPort = 0;
96*38e8c45fSAndroid Build Coastguard Worker auto aiStart = InetSocketAddress::getAddrInfo(address, port);
97*38e8c45fSAndroid Build Coastguard Worker if (aiStart == nullptr) return UNKNOWN_ERROR;
98*38e8c45fSAndroid Build Coastguard Worker for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
99*38e8c45fSAndroid Build Coastguard Worker if (ai->ai_addr == nullptr) continue;
100*38e8c45fSAndroid Build Coastguard Worker InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
101*38e8c45fSAndroid Build Coastguard Worker if (status_t status = setupSocketServer(socketAddress); status != OK) {
102*38e8c45fSAndroid Build Coastguard Worker continue;
103*38e8c45fSAndroid Build Coastguard Worker }
104*38e8c45fSAndroid Build Coastguard Worker
105*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
106*38e8c45fSAndroid Build Coastguard Worker sockaddr_in addr{};
107*38e8c45fSAndroid Build Coastguard Worker socklen_t len = sizeof(addr);
108*38e8c45fSAndroid Build Coastguard Worker if (0 != getsockname(mServer.fd.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
109*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
110*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
111*38e8c45fSAndroid Build Coastguard Worker strerror(savedErrno));
112*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
113*38e8c45fSAndroid Build Coastguard Worker }
114*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
115*38e8c45fSAndroid Build Coastguard Worker static_cast<size_t>(len), sizeof(addr));
116*38e8c45fSAndroid Build Coastguard Worker unsigned int realPort = ntohs(addr.sin_port);
117*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
118*38e8c45fSAndroid Build Coastguard Worker "Requesting inet server on %s but it is set up on %u.",
119*38e8c45fSAndroid Build Coastguard Worker socketAddress.toString().c_str(), realPort);
120*38e8c45fSAndroid Build Coastguard Worker
121*38e8c45fSAndroid Build Coastguard Worker if (assignedPort != nullptr) {
122*38e8c45fSAndroid Build Coastguard Worker *assignedPort = realPort;
123*38e8c45fSAndroid Build Coastguard Worker }
124*38e8c45fSAndroid Build Coastguard Worker
125*38e8c45fSAndroid Build Coastguard Worker return OK;
126*38e8c45fSAndroid Build Coastguard Worker }
127*38e8c45fSAndroid Build Coastguard Worker ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", address,
128*38e8c45fSAndroid Build Coastguard Worker port);
129*38e8c45fSAndroid Build Coastguard Worker return UNKNOWN_ERROR;
130*38e8c45fSAndroid Build Coastguard Worker }
131*38e8c45fSAndroid Build Coastguard Worker
setMaxThreads(size_t threads)132*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setMaxThreads(size_t threads) {
133*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
134*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
135*38e8c45fSAndroid Build Coastguard Worker mMaxThreads = threads;
136*38e8c45fSAndroid Build Coastguard Worker }
137*38e8c45fSAndroid Build Coastguard Worker
getMaxThreads()138*38e8c45fSAndroid Build Coastguard Worker size_t RpcServer::getMaxThreads() {
139*38e8c45fSAndroid Build Coastguard Worker return mMaxThreads;
140*38e8c45fSAndroid Build Coastguard Worker }
141*38e8c45fSAndroid Build Coastguard Worker
setProtocolVersion(uint32_t version)142*38e8c45fSAndroid Build Coastguard Worker bool RpcServer::setProtocolVersion(uint32_t version) {
143*38e8c45fSAndroid Build Coastguard Worker if (!RpcState::validateProtocolVersion(version)) {
144*38e8c45fSAndroid Build Coastguard Worker return false;
145*38e8c45fSAndroid Build Coastguard Worker }
146*38e8c45fSAndroid Build Coastguard Worker
147*38e8c45fSAndroid Build Coastguard Worker mProtocolVersion = version;
148*38e8c45fSAndroid Build Coastguard Worker return true;
149*38e8c45fSAndroid Build Coastguard Worker }
150*38e8c45fSAndroid Build Coastguard Worker
setSupportedFileDescriptorTransportModes(const std::vector<RpcSession::FileDescriptorTransportMode> & modes)151*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setSupportedFileDescriptorTransportModes(
152*38e8c45fSAndroid Build Coastguard Worker const std::vector<RpcSession::FileDescriptorTransportMode>& modes) {
153*38e8c45fSAndroid Build Coastguard Worker mSupportedFileDescriptorTransportModes.reset();
154*38e8c45fSAndroid Build Coastguard Worker for (RpcSession::FileDescriptorTransportMode mode : modes) {
155*38e8c45fSAndroid Build Coastguard Worker mSupportedFileDescriptorTransportModes.set(static_cast<size_t>(mode));
156*38e8c45fSAndroid Build Coastguard Worker }
157*38e8c45fSAndroid Build Coastguard Worker }
158*38e8c45fSAndroid Build Coastguard Worker
setRootObject(const sp<IBinder> & binder)159*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setRootObject(const sp<IBinder>& binder) {
160*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
161*38e8c45fSAndroid Build Coastguard Worker mRootObjectFactory = nullptr;
162*38e8c45fSAndroid Build Coastguard Worker mRootObjectWeak = mRootObject = binder;
163*38e8c45fSAndroid Build Coastguard Worker }
164*38e8c45fSAndroid Build Coastguard Worker
setRootObjectWeak(const wp<IBinder> & binder)165*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
166*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
167*38e8c45fSAndroid Build Coastguard Worker mRootObject.clear();
168*38e8c45fSAndroid Build Coastguard Worker mRootObjectFactory = nullptr;
169*38e8c45fSAndroid Build Coastguard Worker mRootObjectWeak = binder;
170*38e8c45fSAndroid Build Coastguard Worker }
setPerSessionRootObject(std::function<sp<IBinder> (wp<RpcSession> session,const void *,size_t)> && makeObject)171*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setPerSessionRootObject(
172*38e8c45fSAndroid Build Coastguard Worker std::function<sp<IBinder>(wp<RpcSession> session, const void*, size_t)>&& makeObject) {
173*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
174*38e8c45fSAndroid Build Coastguard Worker mRootObject.clear();
175*38e8c45fSAndroid Build Coastguard Worker mRootObjectWeak.clear();
176*38e8c45fSAndroid Build Coastguard Worker mRootObjectFactory = std::move(makeObject);
177*38e8c45fSAndroid Build Coastguard Worker }
178*38e8c45fSAndroid Build Coastguard Worker
setConnectionFilter(std::function<bool (const void *,size_t)> && filter)179*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setConnectionFilter(std::function<bool(const void*, size_t)>&& filter) {
180*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
181*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
182*38e8c45fSAndroid Build Coastguard Worker mConnectionFilter = std::move(filter);
183*38e8c45fSAndroid Build Coastguard Worker }
184*38e8c45fSAndroid Build Coastguard Worker
setServerSocketModifier(std::function<void (borrowed_fd)> && modifier)185*38e8c45fSAndroid Build Coastguard Worker void RpcServer::setServerSocketModifier(std::function<void(borrowed_fd)>&& modifier) {
186*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
187*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mServer.fd.ok(), "Already started");
188*38e8c45fSAndroid Build Coastguard Worker mServerSocketModifier = std::move(modifier);
189*38e8c45fSAndroid Build Coastguard Worker }
190*38e8c45fSAndroid Build Coastguard Worker
getRootObject()191*38e8c45fSAndroid Build Coastguard Worker sp<IBinder> RpcServer::getRootObject() {
192*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
193*38e8c45fSAndroid Build Coastguard Worker bool hasWeak = mRootObjectWeak.unsafe_get();
194*38e8c45fSAndroid Build Coastguard Worker sp<IBinder> ret = mRootObjectWeak.promote();
195*38e8c45fSAndroid Build Coastguard Worker ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
196*38e8c45fSAndroid Build Coastguard Worker return ret;
197*38e8c45fSAndroid Build Coastguard Worker }
198*38e8c45fSAndroid Build Coastguard Worker
getCertificate(RpcCertificateFormat format)199*38e8c45fSAndroid Build Coastguard Worker std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
200*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
201*38e8c45fSAndroid Build Coastguard Worker return mCtx->getCertificate(format);
202*38e8c45fSAndroid Build Coastguard Worker }
203*38e8c45fSAndroid Build Coastguard Worker
joinRpcServer(sp<RpcServer> && thiz)204*38e8c45fSAndroid Build Coastguard Worker static void joinRpcServer(sp<RpcServer>&& thiz) {
205*38e8c45fSAndroid Build Coastguard Worker thiz->join();
206*38e8c45fSAndroid Build Coastguard Worker }
207*38e8c45fSAndroid Build Coastguard Worker
start()208*38e8c45fSAndroid Build Coastguard Worker void RpcServer::start() {
209*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
210*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
211*38e8c45fSAndroid Build Coastguard Worker mJoinThread =
212*38e8c45fSAndroid Build Coastguard Worker std::make_unique<RpcMaybeThread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
213*38e8c45fSAndroid Build Coastguard Worker rpcJoinIfSingleThreaded(*mJoinThread);
214*38e8c45fSAndroid Build Coastguard Worker }
215*38e8c45fSAndroid Build Coastguard Worker
acceptSocketConnection(const RpcServer & server,RpcTransportFd * out)216*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::acceptSocketConnection(const RpcServer& server, RpcTransportFd* out) {
217*38e8c45fSAndroid Build Coastguard Worker RpcTransportFd clientSocket(unique_fd(TEMP_FAILURE_RETRY(
218*38e8c45fSAndroid Build Coastguard Worker accept4(server.mServer.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK))));
219*38e8c45fSAndroid Build Coastguard Worker if (!clientSocket.fd.ok()) {
220*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
221*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not accept4 socket: %s", strerror(savedErrno));
222*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
223*38e8c45fSAndroid Build Coastguard Worker }
224*38e8c45fSAndroid Build Coastguard Worker
225*38e8c45fSAndroid Build Coastguard Worker *out = std::move(clientSocket);
226*38e8c45fSAndroid Build Coastguard Worker return OK;
227*38e8c45fSAndroid Build Coastguard Worker }
228*38e8c45fSAndroid Build Coastguard Worker
recvmsgSocketConnection(const RpcServer & server,RpcTransportFd * out)229*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::recvmsgSocketConnection(const RpcServer& server, RpcTransportFd* out) {
230*38e8c45fSAndroid Build Coastguard Worker int zero = 0;
231*38e8c45fSAndroid Build Coastguard Worker iovec iov{&zero, sizeof(zero)};
232*38e8c45fSAndroid Build Coastguard Worker std::vector<std::variant<unique_fd, borrowed_fd>> fds;
233*38e8c45fSAndroid Build Coastguard Worker
234*38e8c45fSAndroid Build Coastguard Worker ssize_t num_bytes = binder::os::receiveMessageFromSocket(server.mServer, &iov, 1, &fds);
235*38e8c45fSAndroid Build Coastguard Worker if (num_bytes < 0) {
236*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
237*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed recvmsg: %s", strerror(savedErrno));
238*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
239*38e8c45fSAndroid Build Coastguard Worker }
240*38e8c45fSAndroid Build Coastguard Worker if (num_bytes == 0) {
241*38e8c45fSAndroid Build Coastguard Worker return DEAD_OBJECT;
242*38e8c45fSAndroid Build Coastguard Worker }
243*38e8c45fSAndroid Build Coastguard Worker if (fds.size() != 1) {
244*38e8c45fSAndroid Build Coastguard Worker ALOGE("Expected exactly one fd from recvmsg, got %zu", fds.size());
245*38e8c45fSAndroid Build Coastguard Worker return -EINVAL;
246*38e8c45fSAndroid Build Coastguard Worker }
247*38e8c45fSAndroid Build Coastguard Worker
248*38e8c45fSAndroid Build Coastguard Worker unique_fd fd(std::move(std::get<unique_fd>(fds.back())));
249*38e8c45fSAndroid Build Coastguard Worker if (status_t res = binder::os::setNonBlocking(fd); res != OK) return res;
250*38e8c45fSAndroid Build Coastguard Worker
251*38e8c45fSAndroid Build Coastguard Worker *out = RpcTransportFd(std::move(fd));
252*38e8c45fSAndroid Build Coastguard Worker return OK;
253*38e8c45fSAndroid Build Coastguard Worker }
254*38e8c45fSAndroid Build Coastguard Worker
join()255*38e8c45fSAndroid Build Coastguard Worker void RpcServer::join() {
256*38e8c45fSAndroid Build Coastguard Worker
257*38e8c45fSAndroid Build Coastguard Worker {
258*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
259*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(!mServer.fd.ok(), "RpcServer must be setup to join.");
260*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mAcceptFn == nullptr, "RpcServer must have an accept() function");
261*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
262*38e8c45fSAndroid Build Coastguard Worker mJoinThreadRunning = true;
263*38e8c45fSAndroid Build Coastguard Worker mShutdownTrigger = FdTrigger::make();
264*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
265*38e8c45fSAndroid Build Coastguard Worker }
266*38e8c45fSAndroid Build Coastguard Worker
267*38e8c45fSAndroid Build Coastguard Worker status_t status;
268*38e8c45fSAndroid Build Coastguard Worker while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
269*38e8c45fSAndroid Build Coastguard Worker std::array<uint8_t, kRpcAddressSize> addr;
270*38e8c45fSAndroid Build Coastguard Worker static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
271*38e8c45fSAndroid Build Coastguard Worker socklen_t addrLen = addr.size();
272*38e8c45fSAndroid Build Coastguard Worker
273*38e8c45fSAndroid Build Coastguard Worker RpcTransportFd clientSocket;
274*38e8c45fSAndroid Build Coastguard Worker if ((status = mAcceptFn(*this, &clientSocket)) != OK) {
275*38e8c45fSAndroid Build Coastguard Worker if (status == DEAD_OBJECT)
276*38e8c45fSAndroid Build Coastguard Worker break;
277*38e8c45fSAndroid Build Coastguard Worker else
278*38e8c45fSAndroid Build Coastguard Worker continue;
279*38e8c45fSAndroid Build Coastguard Worker }
280*38e8c45fSAndroid Build Coastguard Worker
281*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("accept on fd %d yields fd %d", mServer.fd.get(), clientSocket.fd.get());
282*38e8c45fSAndroid Build Coastguard Worker
283*38e8c45fSAndroid Build Coastguard Worker if (getpeername(clientSocket.fd.get(), reinterpret_cast<sockaddr*>(addr.data()),
284*38e8c45fSAndroid Build Coastguard Worker &addrLen)) {
285*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not getpeername socket: %s", strerror(errno));
286*38e8c45fSAndroid Build Coastguard Worker continue;
287*38e8c45fSAndroid Build Coastguard Worker }
288*38e8c45fSAndroid Build Coastguard Worker
289*38e8c45fSAndroid Build Coastguard Worker if (mConnectionFilter != nullptr && !mConnectionFilter(addr.data(), addrLen)) {
290*38e8c45fSAndroid Build Coastguard Worker ALOGE("Dropped client connection fd %d", clientSocket.fd.get());
291*38e8c45fSAndroid Build Coastguard Worker continue;
292*38e8c45fSAndroid Build Coastguard Worker }
293*38e8c45fSAndroid Build Coastguard Worker
294*38e8c45fSAndroid Build Coastguard Worker {
295*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
296*38e8c45fSAndroid Build Coastguard Worker RpcMaybeThread thread =
297*38e8c45fSAndroid Build Coastguard Worker RpcMaybeThread(&RpcServer::establishConnection,
298*38e8c45fSAndroid Build Coastguard Worker sp<RpcServer>::fromExisting(this), std::move(clientSocket), addr,
299*38e8c45fSAndroid Build Coastguard Worker addrLen, RpcSession::join);
300*38e8c45fSAndroid Build Coastguard Worker
301*38e8c45fSAndroid Build Coastguard Worker auto& threadRef = mConnectingThreads[thread.get_id()];
302*38e8c45fSAndroid Build Coastguard Worker threadRef = std::move(thread);
303*38e8c45fSAndroid Build Coastguard Worker rpcJoinIfSingleThreaded(threadRef);
304*38e8c45fSAndroid Build Coastguard Worker }
305*38e8c45fSAndroid Build Coastguard Worker }
306*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
307*38e8c45fSAndroid Build Coastguard Worker
308*38e8c45fSAndroid Build Coastguard Worker if constexpr (kEnableRpcThreads) {
309*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
310*38e8c45fSAndroid Build Coastguard Worker mJoinThreadRunning = false;
311*38e8c45fSAndroid Build Coastguard Worker } else {
312*38e8c45fSAndroid Build Coastguard Worker // Multi-threaded builds clear this in shutdown(), but we need it valid
313*38e8c45fSAndroid Build Coastguard Worker // so the loop above exits cleanly
314*38e8c45fSAndroid Build Coastguard Worker mShutdownTrigger = nullptr;
315*38e8c45fSAndroid Build Coastguard Worker }
316*38e8c45fSAndroid Build Coastguard Worker mShutdownCv.notify_all();
317*38e8c45fSAndroid Build Coastguard Worker }
318*38e8c45fSAndroid Build Coastguard Worker
shutdown()319*38e8c45fSAndroid Build Coastguard Worker bool RpcServer::shutdown() {
320*38e8c45fSAndroid Build Coastguard Worker RpcMutexUniqueLock _l(mLock);
321*38e8c45fSAndroid Build Coastguard Worker if (mShutdownTrigger == nullptr) {
322*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown, or not "
323*38e8c45fSAndroid Build Coastguard Worker "joined yet?)");
324*38e8c45fSAndroid Build Coastguard Worker return false;
325*38e8c45fSAndroid Build Coastguard Worker }
326*38e8c45fSAndroid Build Coastguard Worker
327*38e8c45fSAndroid Build Coastguard Worker mShutdownTrigger->trigger();
328*38e8c45fSAndroid Build Coastguard Worker
329*38e8c45fSAndroid Build Coastguard Worker for (auto& [id, session] : mSessions) {
330*38e8c45fSAndroid Build Coastguard Worker (void)id;
331*38e8c45fSAndroid Build Coastguard Worker // server lock is a more general lock
332*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _lSession(session->mMutex);
333*38e8c45fSAndroid Build Coastguard Worker session->mShutdownTrigger->trigger();
334*38e8c45fSAndroid Build Coastguard Worker }
335*38e8c45fSAndroid Build Coastguard Worker
336*38e8c45fSAndroid Build Coastguard Worker if constexpr (!kEnableRpcThreads) {
337*38e8c45fSAndroid Build Coastguard Worker // In single-threaded mode we're done here, everything else that
338*38e8c45fSAndroid Build Coastguard Worker // needs to happen should be at the end of RpcServer::join()
339*38e8c45fSAndroid Build Coastguard Worker return true;
340*38e8c45fSAndroid Build Coastguard Worker }
341*38e8c45fSAndroid Build Coastguard Worker
342*38e8c45fSAndroid Build Coastguard Worker while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
343*38e8c45fSAndroid Build Coastguard Worker if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
344*38e8c45fSAndroid Build Coastguard Worker ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
345*38e8c45fSAndroid Build Coastguard Worker "Connecting threads: "
346*38e8c45fSAndroid Build Coastguard Worker "%zu, Sessions: %zu. Is your server deadlocked?",
347*38e8c45fSAndroid Build Coastguard Worker mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
348*38e8c45fSAndroid Build Coastguard Worker }
349*38e8c45fSAndroid Build Coastguard Worker }
350*38e8c45fSAndroid Build Coastguard Worker
351*38e8c45fSAndroid Build Coastguard Worker // At this point, we know join() is about to exit, but the thread that calls
352*38e8c45fSAndroid Build Coastguard Worker // join() may not have exited yet.
353*38e8c45fSAndroid Build Coastguard Worker // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
354*38e8c45fSAndroid Build Coastguard Worker // otherwise ~thread() may call std::terminate(), which may crash the process.
355*38e8c45fSAndroid Build Coastguard Worker // If RpcServer does not own the join thread (aka join() is called directly),
356*38e8c45fSAndroid Build Coastguard Worker // then the owner of RpcServer is responsible for cleaning up that thread.
357*38e8c45fSAndroid Build Coastguard Worker if (mJoinThread.get()) {
358*38e8c45fSAndroid Build Coastguard Worker mJoinThread->join();
359*38e8c45fSAndroid Build Coastguard Worker mJoinThread.reset();
360*38e8c45fSAndroid Build Coastguard Worker }
361*38e8c45fSAndroid Build Coastguard Worker
362*38e8c45fSAndroid Build Coastguard Worker mServer = RpcTransportFd();
363*38e8c45fSAndroid Build Coastguard Worker
364*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("Finished waiting on shutdown.");
365*38e8c45fSAndroid Build Coastguard Worker
366*38e8c45fSAndroid Build Coastguard Worker mShutdownTrigger = nullptr;
367*38e8c45fSAndroid Build Coastguard Worker return true;
368*38e8c45fSAndroid Build Coastguard Worker }
369*38e8c45fSAndroid Build Coastguard Worker
listSessions()370*38e8c45fSAndroid Build Coastguard Worker std::vector<sp<RpcSession>> RpcServer::listSessions() {
371*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
372*38e8c45fSAndroid Build Coastguard Worker std::vector<sp<RpcSession>> sessions;
373*38e8c45fSAndroid Build Coastguard Worker for (auto& [id, session] : mSessions) {
374*38e8c45fSAndroid Build Coastguard Worker (void)id;
375*38e8c45fSAndroid Build Coastguard Worker sessions.push_back(session);
376*38e8c45fSAndroid Build Coastguard Worker }
377*38e8c45fSAndroid Build Coastguard Worker return sessions;
378*38e8c45fSAndroid Build Coastguard Worker }
379*38e8c45fSAndroid Build Coastguard Worker
numUninitializedSessions()380*38e8c45fSAndroid Build Coastguard Worker size_t RpcServer::numUninitializedSessions() {
381*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
382*38e8c45fSAndroid Build Coastguard Worker return mConnectingThreads.size();
383*38e8c45fSAndroid Build Coastguard Worker }
384*38e8c45fSAndroid Build Coastguard Worker
establishConnection(sp<RpcServer> && server,RpcTransportFd clientFd,std::array<uint8_t,kRpcAddressSize> addr,size_t addrLen,std::function<void (sp<RpcSession> &&,RpcSession::PreJoinSetupResult &&)> && joinFn)385*38e8c45fSAndroid Build Coastguard Worker void RpcServer::establishConnection(
386*38e8c45fSAndroid Build Coastguard Worker sp<RpcServer>&& server, RpcTransportFd clientFd, std::array<uint8_t, kRpcAddressSize> addr,
387*38e8c45fSAndroid Build Coastguard Worker size_t addrLen,
388*38e8c45fSAndroid Build Coastguard Worker std::function<void(sp<RpcSession>&&, RpcSession::PreJoinSetupResult&&)>&& joinFn) {
389*38e8c45fSAndroid Build Coastguard Worker // mShutdownTrigger can only be cleared once connection threads have joined.
390*38e8c45fSAndroid Build Coastguard Worker // It must be set before this thread is started
391*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
392*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
393*38e8c45fSAndroid Build Coastguard Worker
394*38e8c45fSAndroid Build Coastguard Worker status_t status = OK;
395*38e8c45fSAndroid Build Coastguard Worker
396*38e8c45fSAndroid Build Coastguard Worker int clientFdForLog = clientFd.fd.get();
397*38e8c45fSAndroid Build Coastguard Worker auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
398*38e8c45fSAndroid Build Coastguard Worker if (client == nullptr) {
399*38e8c45fSAndroid Build Coastguard Worker ALOGE("Dropping accept4()-ed socket because sslAccept fails");
400*38e8c45fSAndroid Build Coastguard Worker status = DEAD_OBJECT;
401*38e8c45fSAndroid Build Coastguard Worker // still need to cleanup before we can return
402*38e8c45fSAndroid Build Coastguard Worker } else {
403*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
404*38e8c45fSAndroid Build Coastguard Worker }
405*38e8c45fSAndroid Build Coastguard Worker
406*38e8c45fSAndroid Build Coastguard Worker RpcConnectionHeader header;
407*38e8c45fSAndroid Build Coastguard Worker if (status == OK) {
408*38e8c45fSAndroid Build Coastguard Worker iovec iov{&header, sizeof(header)};
409*38e8c45fSAndroid Build Coastguard Worker status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
410*38e8c45fSAndroid Build Coastguard Worker std::nullopt, /*ancillaryFds=*/nullptr);
411*38e8c45fSAndroid Build Coastguard Worker if (status != OK) {
412*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed to read ID for client connecting to RPC server: %s",
413*38e8c45fSAndroid Build Coastguard Worker statusToString(status).c_str());
414*38e8c45fSAndroid Build Coastguard Worker // still need to cleanup before we can return
415*38e8c45fSAndroid Build Coastguard Worker }
416*38e8c45fSAndroid Build Coastguard Worker }
417*38e8c45fSAndroid Build Coastguard Worker
418*38e8c45fSAndroid Build Coastguard Worker std::vector<uint8_t> sessionId;
419*38e8c45fSAndroid Build Coastguard Worker if (status == OK) {
420*38e8c45fSAndroid Build Coastguard Worker if (header.sessionIdSize > 0) {
421*38e8c45fSAndroid Build Coastguard Worker if (header.sessionIdSize == kSessionIdBytes) {
422*38e8c45fSAndroid Build Coastguard Worker sessionId.resize(header.sessionIdSize);
423*38e8c45fSAndroid Build Coastguard Worker iovec iov{sessionId.data(), sessionId.size()};
424*38e8c45fSAndroid Build Coastguard Worker status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
425*38e8c45fSAndroid Build Coastguard Worker std::nullopt, /*ancillaryFds=*/nullptr);
426*38e8c45fSAndroid Build Coastguard Worker if (status != OK) {
427*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed to read session ID for client connecting to RPC server: %s",
428*38e8c45fSAndroid Build Coastguard Worker statusToString(status).c_str());
429*38e8c45fSAndroid Build Coastguard Worker // still need to cleanup before we can return
430*38e8c45fSAndroid Build Coastguard Worker }
431*38e8c45fSAndroid Build Coastguard Worker } else {
432*38e8c45fSAndroid Build Coastguard Worker ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
433*38e8c45fSAndroid Build Coastguard Worker kSessionIdBytes, header.sessionIdSize);
434*38e8c45fSAndroid Build Coastguard Worker status = BAD_VALUE;
435*38e8c45fSAndroid Build Coastguard Worker }
436*38e8c45fSAndroid Build Coastguard Worker }
437*38e8c45fSAndroid Build Coastguard Worker }
438*38e8c45fSAndroid Build Coastguard Worker
439*38e8c45fSAndroid Build Coastguard Worker bool incoming = false;
440*38e8c45fSAndroid Build Coastguard Worker uint32_t protocolVersion = 0;
441*38e8c45fSAndroid Build Coastguard Worker bool requestingNewSession = false;
442*38e8c45fSAndroid Build Coastguard Worker
443*38e8c45fSAndroid Build Coastguard Worker if (status == OK) {
444*38e8c45fSAndroid Build Coastguard Worker incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
445*38e8c45fSAndroid Build Coastguard Worker protocolVersion = std::min(header.version,
446*38e8c45fSAndroid Build Coastguard Worker server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
447*38e8c45fSAndroid Build Coastguard Worker requestingNewSession = sessionId.empty();
448*38e8c45fSAndroid Build Coastguard Worker
449*38e8c45fSAndroid Build Coastguard Worker if (requestingNewSession) {
450*38e8c45fSAndroid Build Coastguard Worker RpcNewSessionResponse response{
451*38e8c45fSAndroid Build Coastguard Worker .version = protocolVersion,
452*38e8c45fSAndroid Build Coastguard Worker };
453*38e8c45fSAndroid Build Coastguard Worker
454*38e8c45fSAndroid Build Coastguard Worker iovec iov{&response, sizeof(response)};
455*38e8c45fSAndroid Build Coastguard Worker status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
456*38e8c45fSAndroid Build Coastguard Worker std::nullopt, nullptr);
457*38e8c45fSAndroid Build Coastguard Worker if (status != OK) {
458*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
459*38e8c45fSAndroid Build Coastguard Worker // still need to cleanup before we can return
460*38e8c45fSAndroid Build Coastguard Worker }
461*38e8c45fSAndroid Build Coastguard Worker }
462*38e8c45fSAndroid Build Coastguard Worker }
463*38e8c45fSAndroid Build Coastguard Worker
464*38e8c45fSAndroid Build Coastguard Worker RpcMaybeThread thisThread;
465*38e8c45fSAndroid Build Coastguard Worker sp<RpcSession> session;
466*38e8c45fSAndroid Build Coastguard Worker {
467*38e8c45fSAndroid Build Coastguard Worker RpcMutexUniqueLock _l(server->mLock);
468*38e8c45fSAndroid Build Coastguard Worker
469*38e8c45fSAndroid Build Coastguard Worker auto threadId = server->mConnectingThreads.find(rpc_this_thread::get_id());
470*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
471*38e8c45fSAndroid Build Coastguard Worker "Must establish connection on owned thread");
472*38e8c45fSAndroid Build Coastguard Worker thisThread = std::move(threadId->second);
473*38e8c45fSAndroid Build Coastguard Worker auto detachGuardLambda = [&]() {
474*38e8c45fSAndroid Build Coastguard Worker thisThread.detach();
475*38e8c45fSAndroid Build Coastguard Worker _l.unlock();
476*38e8c45fSAndroid Build Coastguard Worker server->mShutdownCv.notify_all();
477*38e8c45fSAndroid Build Coastguard Worker };
478*38e8c45fSAndroid Build Coastguard Worker auto detachGuard = make_scope_guard(std::ref(detachGuardLambda));
479*38e8c45fSAndroid Build Coastguard Worker server->mConnectingThreads.erase(threadId);
480*38e8c45fSAndroid Build Coastguard Worker
481*38e8c45fSAndroid Build Coastguard Worker if (status != OK || server->mShutdownTrigger->isTriggered()) {
482*38e8c45fSAndroid Build Coastguard Worker return;
483*38e8c45fSAndroid Build Coastguard Worker }
484*38e8c45fSAndroid Build Coastguard Worker
485*38e8c45fSAndroid Build Coastguard Worker if (requestingNewSession) {
486*38e8c45fSAndroid Build Coastguard Worker if (incoming) {
487*38e8c45fSAndroid Build Coastguard Worker ALOGE("Cannot create a new session with an incoming connection, would leak");
488*38e8c45fSAndroid Build Coastguard Worker return;
489*38e8c45fSAndroid Build Coastguard Worker }
490*38e8c45fSAndroid Build Coastguard Worker
491*38e8c45fSAndroid Build Coastguard Worker // Uniquely identify session at the application layer. Even if a
492*38e8c45fSAndroid Build Coastguard Worker // client/server use the same certificates, if they create multiple
493*38e8c45fSAndroid Build Coastguard Worker // sessions, we still want to distinguish between them.
494*38e8c45fSAndroid Build Coastguard Worker sessionId.resize(kSessionIdBytes);
495*38e8c45fSAndroid Build Coastguard Worker size_t tries = 0;
496*38e8c45fSAndroid Build Coastguard Worker do {
497*38e8c45fSAndroid Build Coastguard Worker // don't block if there is some entropy issue
498*38e8c45fSAndroid Build Coastguard Worker if (tries++ > 5) {
499*38e8c45fSAndroid Build Coastguard Worker ALOGE("Cannot find new address: %s",
500*38e8c45fSAndroid Build Coastguard Worker HexString(sessionId.data(), sessionId.size()).c_str());
501*38e8c45fSAndroid Build Coastguard Worker return;
502*38e8c45fSAndroid Build Coastguard Worker }
503*38e8c45fSAndroid Build Coastguard Worker
504*38e8c45fSAndroid Build Coastguard Worker auto status = binder::os::getRandomBytes(sessionId.data(), sessionId.size());
505*38e8c45fSAndroid Build Coastguard Worker if (status != OK) {
506*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed to read random session ID: %s", statusToString(status).c_str());
507*38e8c45fSAndroid Build Coastguard Worker return;
508*38e8c45fSAndroid Build Coastguard Worker }
509*38e8c45fSAndroid Build Coastguard Worker } while (server->mSessions.end() != server->mSessions.find(sessionId));
510*38e8c45fSAndroid Build Coastguard Worker
511*38e8c45fSAndroid Build Coastguard Worker session = sp<RpcSession>::make(nullptr);
512*38e8c45fSAndroid Build Coastguard Worker session->setMaxIncomingThreads(server->mMaxThreads);
513*38e8c45fSAndroid Build Coastguard Worker if (!session->setProtocolVersion(protocolVersion)) return;
514*38e8c45fSAndroid Build Coastguard Worker
515*38e8c45fSAndroid Build Coastguard Worker if (header.fileDescriptorTransportMode <
516*38e8c45fSAndroid Build Coastguard Worker server->mSupportedFileDescriptorTransportModes.size() &&
517*38e8c45fSAndroid Build Coastguard Worker server->mSupportedFileDescriptorTransportModes.test(
518*38e8c45fSAndroid Build Coastguard Worker header.fileDescriptorTransportMode)) {
519*38e8c45fSAndroid Build Coastguard Worker session->setFileDescriptorTransportMode(
520*38e8c45fSAndroid Build Coastguard Worker static_cast<RpcSession::FileDescriptorTransportMode>(
521*38e8c45fSAndroid Build Coastguard Worker header.fileDescriptorTransportMode));
522*38e8c45fSAndroid Build Coastguard Worker } else {
523*38e8c45fSAndroid Build Coastguard Worker ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
524*38e8c45fSAndroid Build Coastguard Worker header.fileDescriptorTransportMode);
525*38e8c45fSAndroid Build Coastguard Worker return;
526*38e8c45fSAndroid Build Coastguard Worker }
527*38e8c45fSAndroid Build Coastguard Worker
528*38e8c45fSAndroid Build Coastguard Worker // if null, falls back to server root
529*38e8c45fSAndroid Build Coastguard Worker sp<IBinder> sessionSpecificRoot;
530*38e8c45fSAndroid Build Coastguard Worker if (server->mRootObjectFactory != nullptr) {
531*38e8c45fSAndroid Build Coastguard Worker sessionSpecificRoot =
532*38e8c45fSAndroid Build Coastguard Worker server->mRootObjectFactory(wp<RpcSession>(session), addr.data(), addrLen);
533*38e8c45fSAndroid Build Coastguard Worker if (sessionSpecificRoot == nullptr) {
534*38e8c45fSAndroid Build Coastguard Worker ALOGE("Warning: server returned null from root object factory");
535*38e8c45fSAndroid Build Coastguard Worker }
536*38e8c45fSAndroid Build Coastguard Worker }
537*38e8c45fSAndroid Build Coastguard Worker
538*38e8c45fSAndroid Build Coastguard Worker if (!session->setForServer(server,
539*38e8c45fSAndroid Build Coastguard Worker sp<RpcServer::EventListener>::fromExisting(
540*38e8c45fSAndroid Build Coastguard Worker static_cast<RpcServer::EventListener*>(
541*38e8c45fSAndroid Build Coastguard Worker server.get())),
542*38e8c45fSAndroid Build Coastguard Worker sessionId, sessionSpecificRoot)) {
543*38e8c45fSAndroid Build Coastguard Worker ALOGE("Failed to attach server to session");
544*38e8c45fSAndroid Build Coastguard Worker return;
545*38e8c45fSAndroid Build Coastguard Worker }
546*38e8c45fSAndroid Build Coastguard Worker
547*38e8c45fSAndroid Build Coastguard Worker server->mSessions[sessionId] = session;
548*38e8c45fSAndroid Build Coastguard Worker } else {
549*38e8c45fSAndroid Build Coastguard Worker auto it = server->mSessions.find(sessionId);
550*38e8c45fSAndroid Build Coastguard Worker if (it == server->mSessions.end()) {
551*38e8c45fSAndroid Build Coastguard Worker ALOGE("Cannot add thread, no record of session with ID %s",
552*38e8c45fSAndroid Build Coastguard Worker HexString(sessionId.data(), sessionId.size()).c_str());
553*38e8c45fSAndroid Build Coastguard Worker return;
554*38e8c45fSAndroid Build Coastguard Worker }
555*38e8c45fSAndroid Build Coastguard Worker session = it->second;
556*38e8c45fSAndroid Build Coastguard Worker }
557*38e8c45fSAndroid Build Coastguard Worker
558*38e8c45fSAndroid Build Coastguard Worker if (incoming) {
559*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
560*38e8c45fSAndroid Build Coastguard Worker "server state must already be initialized");
561*38e8c45fSAndroid Build Coastguard Worker return;
562*38e8c45fSAndroid Build Coastguard Worker }
563*38e8c45fSAndroid Build Coastguard Worker
564*38e8c45fSAndroid Build Coastguard Worker detachGuard.release();
565*38e8c45fSAndroid Build Coastguard Worker session->preJoinThreadOwnership(std::move(thisThread));
566*38e8c45fSAndroid Build Coastguard Worker }
567*38e8c45fSAndroid Build Coastguard Worker
568*38e8c45fSAndroid Build Coastguard Worker auto setupResult = session->preJoinSetup(std::move(client));
569*38e8c45fSAndroid Build Coastguard Worker
570*38e8c45fSAndroid Build Coastguard Worker // avoid strong cycle
571*38e8c45fSAndroid Build Coastguard Worker server = nullptr;
572*38e8c45fSAndroid Build Coastguard Worker
573*38e8c45fSAndroid Build Coastguard Worker joinFn(std::move(session), std::move(setupResult));
574*38e8c45fSAndroid Build Coastguard Worker }
575*38e8c45fSAndroid Build Coastguard Worker
setupSocketServer(const RpcSocketAddress & addr)576*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
577*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
578*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
579*38e8c45fSAndroid Build Coastguard Worker
580*38e8c45fSAndroid Build Coastguard Worker unique_fd socket_fd(TEMP_FAILURE_RETRY(
581*38e8c45fSAndroid Build Coastguard Worker socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
582*38e8c45fSAndroid Build Coastguard Worker if (!socket_fd.ok()) {
583*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
584*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
585*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
586*38e8c45fSAndroid Build Coastguard Worker }
587*38e8c45fSAndroid Build Coastguard Worker
588*38e8c45fSAndroid Build Coastguard Worker if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
589*38e8c45fSAndroid Build Coastguard Worker int noDelay = 1;
590*38e8c45fSAndroid Build Coastguard Worker int result =
591*38e8c45fSAndroid Build Coastguard Worker setsockopt(socket_fd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
592*38e8c45fSAndroid Build Coastguard Worker if (result < 0) {
593*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
594*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not set TCP_NODELAY on %s", strerror(savedErrno));
595*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
596*38e8c45fSAndroid Build Coastguard Worker }
597*38e8c45fSAndroid Build Coastguard Worker }
598*38e8c45fSAndroid Build Coastguard Worker
599*38e8c45fSAndroid Build Coastguard Worker {
600*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
601*38e8c45fSAndroid Build Coastguard Worker if (mServerSocketModifier != nullptr) {
602*38e8c45fSAndroid Build Coastguard Worker mServerSocketModifier(socket_fd);
603*38e8c45fSAndroid Build Coastguard Worker }
604*38e8c45fSAndroid Build Coastguard Worker }
605*38e8c45fSAndroid Build Coastguard Worker
606*38e8c45fSAndroid Build Coastguard Worker if (0 != TEMP_FAILURE_RETRY(bind(socket_fd.get(), addr.addr(), addr.addrSize()))) {
607*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
608*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
609*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
610*38e8c45fSAndroid Build Coastguard Worker }
611*38e8c45fSAndroid Build Coastguard Worker
612*38e8c45fSAndroid Build Coastguard Worker return setupRawSocketServer(std::move(socket_fd));
613*38e8c45fSAndroid Build Coastguard Worker }
614*38e8c45fSAndroid Build Coastguard Worker
setupRawSocketServer(unique_fd socket_fd)615*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupRawSocketServer(unique_fd socket_fd) {
616*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(!socket_fd.ok(), "Socket must be setup to listen.");
617*38e8c45fSAndroid Build Coastguard Worker
618*38e8c45fSAndroid Build Coastguard Worker // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
619*38e8c45fSAndroid Build Coastguard Worker // the backlog is increased to a large number.
620*38e8c45fSAndroid Build Coastguard Worker // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
621*38e8c45fSAndroid Build Coastguard Worker // to 1.
622*38e8c45fSAndroid Build Coastguard Worker if (0 != TEMP_FAILURE_RETRY(listen(socket_fd.get(), 50 /*backlog*/))) {
623*38e8c45fSAndroid Build Coastguard Worker int savedErrno = errno;
624*38e8c45fSAndroid Build Coastguard Worker ALOGE("Could not listen initialized Unix socket: %s", strerror(savedErrno));
625*38e8c45fSAndroid Build Coastguard Worker return -savedErrno;
626*38e8c45fSAndroid Build Coastguard Worker }
627*38e8c45fSAndroid Build Coastguard Worker if (status_t status = setupExternalServer(std::move(socket_fd)); status != OK) {
628*38e8c45fSAndroid Build Coastguard Worker ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
629*38e8c45fSAndroid Build Coastguard Worker return status;
630*38e8c45fSAndroid Build Coastguard Worker }
631*38e8c45fSAndroid Build Coastguard Worker return OK;
632*38e8c45fSAndroid Build Coastguard Worker }
633*38e8c45fSAndroid Build Coastguard Worker
onSessionAllIncomingThreadsEnded(const sp<RpcSession> & session)634*38e8c45fSAndroid Build Coastguard Worker void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
635*38e8c45fSAndroid Build Coastguard Worker const std::vector<uint8_t>& id = session->mId;
636*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
637*38e8c45fSAndroid Build Coastguard Worker LOG_RPC_DETAIL("Dropping session with address %s", HexString(id.data(), id.size()).c_str());
638*38e8c45fSAndroid Build Coastguard Worker
639*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
640*38e8c45fSAndroid Build Coastguard Worker auto it = mSessions.find(id);
641*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
642*38e8c45fSAndroid Build Coastguard Worker HexString(id.data(), id.size()).c_str());
643*38e8c45fSAndroid Build Coastguard Worker LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
644*38e8c45fSAndroid Build Coastguard Worker HexString(id.data(), id.size()).c_str());
645*38e8c45fSAndroid Build Coastguard Worker (void)mSessions.erase(it);
646*38e8c45fSAndroid Build Coastguard Worker }
647*38e8c45fSAndroid Build Coastguard Worker
onSessionIncomingThreadEnded()648*38e8c45fSAndroid Build Coastguard Worker void RpcServer::onSessionIncomingThreadEnded() {
649*38e8c45fSAndroid Build Coastguard Worker mShutdownCv.notify_all();
650*38e8c45fSAndroid Build Coastguard Worker }
651*38e8c45fSAndroid Build Coastguard Worker
hasServer()652*38e8c45fSAndroid Build Coastguard Worker bool RpcServer::hasServer() {
653*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
654*38e8c45fSAndroid Build Coastguard Worker return mServer.fd.ok();
655*38e8c45fSAndroid Build Coastguard Worker }
656*38e8c45fSAndroid Build Coastguard Worker
releaseServer()657*38e8c45fSAndroid Build Coastguard Worker unique_fd RpcServer::releaseServer() {
658*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
659*38e8c45fSAndroid Build Coastguard Worker return std::move(mServer.fd);
660*38e8c45fSAndroid Build Coastguard Worker }
661*38e8c45fSAndroid Build Coastguard Worker
setupExternalServer(unique_fd serverFd,std::function<status_t (const RpcServer &,RpcTransportFd *)> && acceptFn)662*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupExternalServer(
663*38e8c45fSAndroid Build Coastguard Worker unique_fd serverFd, std::function<status_t(const RpcServer&, RpcTransportFd*)>&& acceptFn) {
664*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
665*38e8c45fSAndroid Build Coastguard Worker if (mServer.fd.ok()) {
666*38e8c45fSAndroid Build Coastguard Worker ALOGE("Each RpcServer can only have one server.");
667*38e8c45fSAndroid Build Coastguard Worker return INVALID_OPERATION;
668*38e8c45fSAndroid Build Coastguard Worker }
669*38e8c45fSAndroid Build Coastguard Worker mServer = std::move(serverFd);
670*38e8c45fSAndroid Build Coastguard Worker mAcceptFn = std::move(acceptFn);
671*38e8c45fSAndroid Build Coastguard Worker return OK;
672*38e8c45fSAndroid Build Coastguard Worker }
673*38e8c45fSAndroid Build Coastguard Worker
setupExternalServer(unique_fd serverFd)674*38e8c45fSAndroid Build Coastguard Worker status_t RpcServer::setupExternalServer(unique_fd serverFd) {
675*38e8c45fSAndroid Build Coastguard Worker return setupExternalServer(std::move(serverFd), &RpcServer::acceptSocketConnection);
676*38e8c45fSAndroid Build Coastguard Worker }
677*38e8c45fSAndroid Build Coastguard Worker
hasActiveRequests()678*38e8c45fSAndroid Build Coastguard Worker bool RpcServer::hasActiveRequests() {
679*38e8c45fSAndroid Build Coastguard Worker RpcMutexLockGuard _l(mLock);
680*38e8c45fSAndroid Build Coastguard Worker for (const auto& [_, session] : mSessions) {
681*38e8c45fSAndroid Build Coastguard Worker if (session->hasActiveRequests()) {
682*38e8c45fSAndroid Build Coastguard Worker return true;
683*38e8c45fSAndroid Build Coastguard Worker }
684*38e8c45fSAndroid Build Coastguard Worker }
685*38e8c45fSAndroid Build Coastguard Worker return !mServer.isInPollingState();
686*38e8c45fSAndroid Build Coastguard Worker }
687*38e8c45fSAndroid Build Coastguard Worker
688*38e8c45fSAndroid Build Coastguard Worker } // namespace android
689