blob: 05e0f37abe425e070142ecd0b3e798015647cdee [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
Yifan Hong8c950422021-08-05 17:13:55 -070035#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000036#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070037#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038#include "RpcWireFormat.h"
Andrei Homescuc24c8792022-04-19 00:24:51 +000039#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000040
41namespace android {
42
Steven Morelandc5032042021-09-30 15:40:27 -070043constexpr size_t kSessionIdBytes = 32;
44
Steven Moreland5802c2b2021-05-12 20:13:04 +000045using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000046using base::unique_fd;
47
Yifan Hongecf937d2021-08-11 17:29:28 -070048RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070049RpcServer::~RpcServer() {
50 (void)shutdown();
51}
Steven Moreland5553ac42020-11-11 02:14:45 +000052
Yifan Hong702115c2021-06-24 15:39:18 -070053sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
54 // Default is without TLS.
55 if (rpcTransportCtxFactory == nullptr)
56 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070057 auto ctx = rpcTransportCtxFactory->newServerCtx();
58 if (ctx == nullptr) return nullptr;
59 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000060}
61
Steven Moreland2372f9d2021-08-05 15:42:01 -070062status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000063 return setupSocketServer(UnixSocketAddress(path));
64}
65
Steven Moreland2372f9d2021-08-05 15:42:01 -070066status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000067 // realizing value w/ this type at compile time to avoid ubsan abort
68 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
69
70 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
71}
72
Steven Moreland2372f9d2021-08-05 15:42:01 -070073status_t RpcServer::setupInetServer(const char* address, unsigned int port,
74 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000075 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000076 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070077 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000078 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000079 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070080 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000081 continue;
82 }
83
84 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
85 sockaddr_in addr{};
86 socklen_t len = sizeof(addr);
87 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
88 int savedErrno = errno;
89 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
90 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070091 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000092 }
93 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
94 static_cast<size_t>(len), sizeof(addr));
95 unsigned int realPort = ntohs(addr.sin_port);
96 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
97 "Requesting inet server on %s but it is set up on %u.",
98 socketAddress.toString().c_str(), realPort);
99
100 if (assignedPort != nullptr) {
101 *assignedPort = realPort;
102 }
103
Steven Moreland2372f9d2021-08-05 15:42:01 -0700104 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000105 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000106 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 +0000107 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700108 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000109}
110
Steven Morelandf137de92021-04-24 01:54:26 +0000111void RpcServer::setMaxThreads(size_t threads) {
112 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700113 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000114 mMaxThreads = threads;
115}
116
117size_t RpcServer::getMaxThreads() {
118 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119}
120
Steven Morelandbf57bce2021-07-26 15:26:12 -0700121void RpcServer::setProtocolVersion(uint32_t version) {
122 mProtocolVersion = version;
123}
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000126 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700127 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700128 mRootObjectWeak = mRootObject = binder;
129}
130
131void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
132 std::lock_guard<std::mutex> _l(mLock);
133 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700134 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700135 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000136}
Steven Moreland51c44a92021-10-14 16:50:35 -0700137void RpcServer::setPerSessionRootObject(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000138 std::function<sp<IBinder>(const void*, size_t)>&& makeObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700139 std::lock_guard<std::mutex> _l(mLock);
140 mRootObject.clear();
141 mRootObjectWeak.clear();
142 mRootObjectFactory = std::move(makeObject);
143}
Steven Moreland5553ac42020-11-11 02:14:45 +0000144
145sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000146 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700147 bool hasWeak = mRootObjectWeak.unsafe_get();
148 sp<IBinder> ret = mRootObjectWeak.promote();
149 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
150 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000151}
152
Yifan Hong9734cfc2021-09-13 16:14:09 -0700153std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700154 std::lock_guard<std::mutex> _l(mLock);
155 return mCtx->getCertificate(format);
156}
157
Yifan Hong326afd12021-05-19 15:24:54 -0700158static void joinRpcServer(sp<RpcServer>&& thiz) {
159 thiz->join();
160}
161
162void RpcServer::start() {
Yifan Hong326afd12021-05-19 15:24:54 -0700163 std::lock_guard<std::mutex> _l(mLock);
164 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
165 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
166}
167
Steven Moreland611d15f2021-05-01 01:28:27 +0000168void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700169
170 {
171 std::lock_guard<std::mutex> _l(mLock);
172 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
173 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
174 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700175 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700176 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000177 }
Yifan Hong1a235852021-05-13 16:07:47 -0700178
Steven Moreland2b4f3802021-05-22 01:46:27 +0000179 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000180 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000181 std::array<uint8_t, kRpcAddressSize> addr;
182 static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
Steven Moreland51c44a92021-10-14 16:50:35 -0700183
Andrei Homescu86124ca2022-04-21 22:22:48 +0000184 socklen_t addrLen = addr.size();
Steven Moreland51c44a92021-10-14 16:50:35 -0700185 unique_fd clientFd(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000186 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(addr.data()),
Steven Moreland51c44a92021-10-14 16:50:35 -0700187 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
188
Andrei Homescu86124ca2022-04-21 22:22:48 +0000189 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(sockaddr_storage)),
190 "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000191
192 if (clientFd < 0) {
193 ALOGE("Could not accept4 socket: %s", strerror(errno));
194 continue;
195 }
196 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
197
198 {
199 std::lock_guard<std::mutex> _l(mLock);
200 std::thread thread =
201 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
Steven Moreland51c44a92021-10-14 16:50:35 -0700202 std::move(clientFd), addr, addrLen);
Steven Moreland410325a2021-06-02 18:37:42 +0000203 mConnectingThreads[thread.get_id()] = std::move(thread);
204 }
Yifan Hong1a235852021-05-13 16:07:47 -0700205 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000206 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700207
208 {
209 std::lock_guard<std::mutex> _l(mLock);
210 mJoinThreadRunning = false;
211 }
212 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000213}
214
Yifan Hong1a235852021-05-13 16:07:47 -0700215bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700216 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000217 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000218 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000219 return false;
220 }
Yifan Hong1a235852021-05-13 16:07:47 -0700221
222 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700223
Steven Morelanda8b44292021-06-08 01:27:53 +0000224 for (auto& [id, session] : mSessions) {
225 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700226 // server lock is a more general lock
227 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000228 session->mShutdownTrigger->trigger();
229 }
230
Steven Morelandee3f4662021-05-22 01:07:33 +0000231 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000232 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
233 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
234 "Connecting threads: "
235 "%zu, Sessions: %zu. Is your server deadlocked?",
236 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
237 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000238 }
Yifan Hong1a235852021-05-13 16:07:47 -0700239
Yifan Hong326afd12021-05-19 15:24:54 -0700240 // At this point, we know join() is about to exit, but the thread that calls
241 // join() may not have exited yet.
242 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
243 // otherwise ~thread() may call std::terminate(), which may crash the process.
244 // If RpcServer does not own the join thread (aka join() is called directly),
245 // then the owner of RpcServer is responsible for cleaning up that thread.
246 if (mJoinThread.get()) {
247 mJoinThread->join();
248 mJoinThread.reset();
249 }
250
Steven Moreland1c943ec2021-07-13 23:57:56 +0000251 LOG_RPC_DETAIL("Finished waiting on shutdown.");
252
Yifan Hong1a235852021-05-13 16:07:47 -0700253 mShutdownTrigger = nullptr;
254 return true;
255}
256
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000258 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259 std::vector<sp<RpcSession>> sessions;
260 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000261 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000263 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000264 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000265}
266
Steven Morelandd539fbf2021-05-05 23:40:25 +0000267size_t RpcServer::numUninitializedSessions() {
268 std::lock_guard<std::mutex> _l(mLock);
269 return mConnectingThreads.size();
270}
271
Steven Moreland51c44a92021-10-14 16:50:35 -0700272void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
Andrei Homescu86124ca2022-04-21 22:22:48 +0000273 std::array<uint8_t, kRpcAddressSize> addr, size_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000274 // mShutdownTrigger can only be cleared once connection threads have joined.
275 // It must be set before this thread is started
276 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700277 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
278
279 status_t status = OK;
280
281 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700282 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700283 if (client == nullptr) {
284 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
285 status = DEAD_OBJECT;
286 // still need to cleanup before we can return
287 } else {
288 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
289 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000290
Steven Moreland659416d2021-05-11 00:47:50 +0000291 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700292 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000293 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000294 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
295 std::nullopt);
Yifan Hong702115c2021-06-24 15:39:18 -0700296 if (status != OK) {
297 ALOGE("Failed to read ID for client connecting to RPC server: %s",
298 statusToString(status).c_str());
299 // still need to cleanup before we can return
300 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000301 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700302
Steven Moreland826367f2021-09-10 14:05:31 -0700303 std::vector<uint8_t> sessionId;
304 if (status == OK) {
305 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700306 if (header.sessionIdSize == kSessionIdBytes) {
307 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000308 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000309 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
310 std::nullopt);
Steven Morelandc5032042021-09-30 15:40:27 -0700311 if (status != OK) {
312 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
313 statusToString(status).c_str());
314 // still need to cleanup before we can return
315 }
316 } else {
317 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
318 kSessionIdBytes, header.sessionIdSize);
319 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700320 }
321 }
322 }
323
Steven Morelandbf57bce2021-07-26 15:26:12 -0700324 bool incoming = false;
325 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700326 bool requestingNewSession = false;
327
328 if (status == OK) {
329 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
330 protocolVersion = std::min(header.version,
331 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700332 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700333
334 if (requestingNewSession) {
335 RpcNewSessionResponse response{
336 .version = protocolVersion,
337 };
338
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000339 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000340 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
341 std::nullopt);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700342 if (status != OK) {
343 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
344 // still need to cleanup before we can return
345 }
346 }
347 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000348
349 std::thread thisThread;
350 sp<RpcSession> session;
351 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000352 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000353
Yifan Hongb3005502021-05-19 15:37:00 -0700354 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
355 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000356 "Must establish connection on owned thread");
357 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000358 ScopeGuard detachGuard = [&]() {
359 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000360 _l.unlock();
361 server->mShutdownCv.notify_all();
362 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000363 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000364
Steven Morelandbf57bce2021-07-26 15:26:12 -0700365 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000366 return;
367 }
368
Steven Morelandbf57bce2021-07-26 15:26:12 -0700369 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000370 if (incoming) {
371 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000372 return;
373 }
374
Steven Moreland826367f2021-09-10 14:05:31 -0700375 // Uniquely identify session at the application layer. Even if a
376 // client/server use the same certificates, if they create multiple
377 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700378 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000379 size_t tries = 0;
380 do {
381 // don't block if there is some entropy issue
382 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700383 ALOGE("Cannot find new address: %s",
384 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000385 return;
386 }
387
Andrei Homescuc24c8792022-04-19 00:24:51 +0000388 auto status = getRandomBytes(sessionId.data(), sessionId.size());
389 if (status != OK) {
390 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700391 return;
392 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000393 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000394
395 session = RpcSession::make();
Yifan Hong10423062021-10-08 16:26:32 -0700396 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700397 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700398
399 // if null, falls back to server root
400 sp<IBinder> sessionSpecificRoot;
401 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000402 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700403 if (sessionSpecificRoot == nullptr) {
404 ALOGE("Warning: server returned null from root object factory");
405 }
406 }
407
Steven Morelanda8b44292021-06-08 01:27:53 +0000408 if (!session->setForServer(server,
409 sp<RpcServer::EventListener>::fromExisting(
410 static_cast<RpcServer::EventListener*>(
411 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700412 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000413 ALOGE("Failed to attach server to session");
414 return;
415 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000416
Steven Moreland01a6bad2021-06-11 00:59:20 +0000417 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000418 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000419 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700420 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000421 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700422 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000423 return;
424 }
425 session = it->second;
426 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000427
Steven Moreland1b304292021-07-15 22:59:34 +0000428 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700429 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000430 "server state must already be initialized");
431 return;
432 }
433
Steven Moreland5802c2b2021-05-12 20:13:04 +0000434 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000435 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000436 }
437
Yifan Hong702115c2021-06-24 15:39:18 -0700438 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000439
Steven Morelanda63ff932021-05-12 00:03:15 +0000440 // avoid strong cycle
441 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000442
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000443 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000444}
445
Steven Moreland2372f9d2021-08-05 15:42:01 -0700446status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000447 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700448 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000449
Yifan Hongb675ffe2021-08-05 16:37:17 -0700450 unique_fd serverFd(TEMP_FAILURE_RETRY(
451 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000452 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700453 int savedErrno = errno;
454 ALOGE("Could not create socket: %s", strerror(savedErrno));
455 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000456 }
457
458 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
459 int savedErrno = errno;
460 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700461 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000462 }
463
Yifan Honge96a1f12021-07-13 16:08:28 -0700464 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
465 // the backlog is increased to a large number.
466 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
467 // to 1.
468 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000469 int savedErrno = errno;
470 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700471 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000472 }
473
Steven Moreland704fc1a2021-05-04 23:13:14 +0000474 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
475
Steven Moreland2372f9d2021-08-05 15:42:01 -0700476 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700477 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700478 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700479 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000481}
482
Steven Morelanddd67b942021-07-23 17:15:41 -0700483void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700484 const std::vector<uint8_t>& id = session->mId;
485 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
486 LOG_RPC_DETAIL("Dropping session with address %s",
487 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000488
489 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700490 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000491 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700492 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000493 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700494 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000495 (void)mSessions.erase(it);
496}
497
Steven Moreland19fc9f72021-06-10 03:57:30 +0000498void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000499 mShutdownCv.notify_all();
500}
501
Yifan Hong0eb5a672021-05-12 18:00:25 -0700502bool RpcServer::hasServer() {
503 std::lock_guard<std::mutex> _l(mLock);
504 return mServer.ok();
505}
506
Yifan Hong00aeb762021-05-12 17:07:36 -0700507unique_fd RpcServer::releaseServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700508 std::lock_guard<std::mutex> _l(mLock);
509 return std::move(mServer);
510}
511
Steven Moreland2372f9d2021-08-05 15:42:01 -0700512status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700513 std::lock_guard<std::mutex> _l(mLock);
514 if (mServer.ok()) {
515 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700516 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700517 }
518 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700519 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700520}
521
Steven Moreland5553ac42020-11-11 02:14:45 +0000522} // namespace android