blob: f83bb5e335dc36daafe803f32bca96029c0e757e [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
Frederick Mayle69a0c992022-05-26 20:38:39 +0000125void RpcServer::setSupportedFileDescriptorTransportModes(
126 const std::vector<RpcSession::FileDescriptorTransportMode>& modes) {
127 mSupportedFileDescriptorTransportModes.reset();
128 for (RpcSession::FileDescriptorTransportMode mode : modes) {
129 mSupportedFileDescriptorTransportModes.set(static_cast<size_t>(mode));
130 }
131}
132
Steven Moreland5553ac42020-11-11 02:14:45 +0000133void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000134 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700135 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700136 mRootObjectWeak = mRootObject = binder;
137}
138
139void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
140 std::lock_guard<std::mutex> _l(mLock);
141 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700142 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700143 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000144}
Steven Moreland51c44a92021-10-14 16:50:35 -0700145void RpcServer::setPerSessionRootObject(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000146 std::function<sp<IBinder>(const void*, size_t)>&& makeObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700147 std::lock_guard<std::mutex> _l(mLock);
148 mRootObject.clear();
149 mRootObjectWeak.clear();
150 mRootObjectFactory = std::move(makeObject);
151}
Steven Moreland5553ac42020-11-11 02:14:45 +0000152
153sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000154 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700155 bool hasWeak = mRootObjectWeak.unsafe_get();
156 sp<IBinder> ret = mRootObjectWeak.promote();
157 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
158 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000159}
160
Yifan Hong9734cfc2021-09-13 16:14:09 -0700161std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700162 std::lock_guard<std::mutex> _l(mLock);
163 return mCtx->getCertificate(format);
164}
165
Yifan Hong326afd12021-05-19 15:24:54 -0700166static void joinRpcServer(sp<RpcServer>&& thiz) {
167 thiz->join();
168}
169
170void RpcServer::start() {
Yifan Hong326afd12021-05-19 15:24:54 -0700171 std::lock_guard<std::mutex> _l(mLock);
172 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
173 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
174}
175
Steven Moreland611d15f2021-05-01 01:28:27 +0000176void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700177
178 {
179 std::lock_guard<std::mutex> _l(mLock);
180 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
181 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
182 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700183 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700184 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000185 }
Yifan Hong1a235852021-05-13 16:07:47 -0700186
Steven Moreland2b4f3802021-05-22 01:46:27 +0000187 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000188 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000189 std::array<uint8_t, kRpcAddressSize> addr;
190 static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
Steven Moreland51c44a92021-10-14 16:50:35 -0700191
Andrei Homescu86124ca2022-04-21 22:22:48 +0000192 socklen_t addrLen = addr.size();
Steven Moreland51c44a92021-10-14 16:50:35 -0700193 unique_fd clientFd(
Andrei Homescu86124ca2022-04-21 22:22:48 +0000194 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(addr.data()),
Steven Moreland51c44a92021-10-14 16:50:35 -0700195 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
196
Andrei Homescu86124ca2022-04-21 22:22:48 +0000197 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(sockaddr_storage)),
198 "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000199
200 if (clientFd < 0) {
201 ALOGE("Could not accept4 socket: %s", strerror(errno));
202 continue;
203 }
204 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
205
206 {
207 std::lock_guard<std::mutex> _l(mLock);
208 std::thread thread =
209 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
Steven Moreland51c44a92021-10-14 16:50:35 -0700210 std::move(clientFd), addr, addrLen);
Steven Moreland410325a2021-06-02 18:37:42 +0000211 mConnectingThreads[thread.get_id()] = std::move(thread);
212 }
Yifan Hong1a235852021-05-13 16:07:47 -0700213 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000214 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700215
216 {
217 std::lock_guard<std::mutex> _l(mLock);
218 mJoinThreadRunning = false;
219 }
220 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000221}
222
Yifan Hong1a235852021-05-13 16:07:47 -0700223bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700224 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000225 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000226 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000227 return false;
228 }
Yifan Hong1a235852021-05-13 16:07:47 -0700229
230 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700231
Steven Morelanda8b44292021-06-08 01:27:53 +0000232 for (auto& [id, session] : mSessions) {
233 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700234 // server lock is a more general lock
235 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000236 session->mShutdownTrigger->trigger();
237 }
238
Steven Morelandee3f4662021-05-22 01:07:33 +0000239 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000240 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
241 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
242 "Connecting threads: "
243 "%zu, Sessions: %zu. Is your server deadlocked?",
244 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
245 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000246 }
Yifan Hong1a235852021-05-13 16:07:47 -0700247
Yifan Hong326afd12021-05-19 15:24:54 -0700248 // At this point, we know join() is about to exit, but the thread that calls
249 // join() may not have exited yet.
250 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
251 // otherwise ~thread() may call std::terminate(), which may crash the process.
252 // If RpcServer does not own the join thread (aka join() is called directly),
253 // then the owner of RpcServer is responsible for cleaning up that thread.
254 if (mJoinThread.get()) {
255 mJoinThread->join();
256 mJoinThread.reset();
257 }
258
Steven Moreland1c943ec2021-07-13 23:57:56 +0000259 LOG_RPC_DETAIL("Finished waiting on shutdown.");
260
Yifan Hong1a235852021-05-13 16:07:47 -0700261 mShutdownTrigger = nullptr;
262 return true;
263}
264
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000266 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267 std::vector<sp<RpcSession>> sessions;
268 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000269 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000271 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000272 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000273}
274
Steven Morelandd539fbf2021-05-05 23:40:25 +0000275size_t RpcServer::numUninitializedSessions() {
276 std::lock_guard<std::mutex> _l(mLock);
277 return mConnectingThreads.size();
278}
279
Steven Moreland51c44a92021-10-14 16:50:35 -0700280void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
Andrei Homescu86124ca2022-04-21 22:22:48 +0000281 std::array<uint8_t, kRpcAddressSize> addr, size_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000282 // mShutdownTrigger can only be cleared once connection threads have joined.
283 // It must be set before this thread is started
284 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700285 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
286
287 status_t status = OK;
288
289 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700290 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700291 if (client == nullptr) {
292 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
293 status = DEAD_OBJECT;
294 // still need to cleanup before we can return
295 } else {
296 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
297 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000298
Steven Moreland659416d2021-05-11 00:47:50 +0000299 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700300 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000301 iovec iov{&header, sizeof(header)};
Devin Moore695368f2022-06-03 22:29:14 +0000302 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000303 std::nullopt, /*ancillaryFds=*/nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700304 if (status != OK) {
305 ALOGE("Failed to read ID for client connecting to RPC server: %s",
306 statusToString(status).c_str());
307 // still need to cleanup before we can return
308 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000309 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700310
Steven Moreland826367f2021-09-10 14:05:31 -0700311 std::vector<uint8_t> sessionId;
312 if (status == OK) {
313 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700314 if (header.sessionIdSize == kSessionIdBytes) {
315 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000316 iovec iov{sessionId.data(), sessionId.size()};
Devin Moore695368f2022-06-03 22:29:14 +0000317 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000318 std::nullopt, /*ancillaryFds=*/nullptr);
Steven Morelandc5032042021-09-30 15:40:27 -0700319 if (status != OK) {
320 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
321 statusToString(status).c_str());
322 // still need to cleanup before we can return
323 }
324 } else {
325 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
326 kSessionIdBytes, header.sessionIdSize);
327 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700328 }
329 }
330 }
331
Steven Morelandbf57bce2021-07-26 15:26:12 -0700332 bool incoming = false;
333 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700334 bool requestingNewSession = false;
335
336 if (status == OK) {
337 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
338 protocolVersion = std::min(header.version,
339 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700340 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700341
342 if (requestingNewSession) {
343 RpcNewSessionResponse response{
344 .version = protocolVersion,
345 };
346
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000347 iovec iov{&response, sizeof(response)};
Devin Moore695368f2022-06-03 22:29:14 +0000348 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000349 std::nullopt, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700350 if (status != OK) {
351 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
352 // still need to cleanup before we can return
353 }
354 }
355 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000356
357 std::thread thisThread;
358 sp<RpcSession> session;
359 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000360 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000361
Yifan Hongb3005502021-05-19 15:37:00 -0700362 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
363 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000364 "Must establish connection on owned thread");
365 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000366 ScopeGuard detachGuard = [&]() {
367 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000368 _l.unlock();
369 server->mShutdownCv.notify_all();
370 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000371 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000372
Steven Morelandbf57bce2021-07-26 15:26:12 -0700373 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000374 return;
375 }
376
Steven Morelandbf57bce2021-07-26 15:26:12 -0700377 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000378 if (incoming) {
379 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000380 return;
381 }
382
Steven Moreland826367f2021-09-10 14:05:31 -0700383 // Uniquely identify session at the application layer. Even if a
384 // client/server use the same certificates, if they create multiple
385 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700386 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000387 size_t tries = 0;
388 do {
389 // don't block if there is some entropy issue
390 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700391 ALOGE("Cannot find new address: %s",
392 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000393 return;
394 }
395
Andrei Homescuc24c8792022-04-19 00:24:51 +0000396 auto status = getRandomBytes(sessionId.data(), sessionId.size());
397 if (status != OK) {
398 ALOGE("Failed to read random session ID: %s", strerror(-status));
Steven Moreland826367f2021-09-10 14:05:31 -0700399 return;
400 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000401 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000402
Andrei Homescu5e301462022-05-12 00:52:34 +0000403 session = sp<RpcSession>::make(nullptr);
Yifan Hong10423062021-10-08 16:26:32 -0700404 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700405 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700406
Frederick Mayle69a0c992022-05-26 20:38:39 +0000407 if (server->mSupportedFileDescriptorTransportModes.test(
408 header.fileDescriptorTransportMode)) {
409 session->setFileDescriptorTransportMode(
410 static_cast<RpcSession::FileDescriptorTransportMode>(
411 header.fileDescriptorTransportMode));
412 } else {
413 ALOGE("Rejecting connection: FileDescriptorTransportMode is not supported: %hhu",
414 header.fileDescriptorTransportMode);
415 return;
416 }
417
Steven Moreland51c44a92021-10-14 16:50:35 -0700418 // if null, falls back to server root
419 sp<IBinder> sessionSpecificRoot;
420 if (server->mRootObjectFactory != nullptr) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000421 sessionSpecificRoot = server->mRootObjectFactory(addr.data(), addrLen);
Steven Moreland51c44a92021-10-14 16:50:35 -0700422 if (sessionSpecificRoot == nullptr) {
423 ALOGE("Warning: server returned null from root object factory");
424 }
425 }
426
Steven Morelanda8b44292021-06-08 01:27:53 +0000427 if (!session->setForServer(server,
428 sp<RpcServer::EventListener>::fromExisting(
429 static_cast<RpcServer::EventListener*>(
430 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700431 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000432 ALOGE("Failed to attach server to session");
433 return;
434 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000435
Steven Moreland01a6bad2021-06-11 00:59:20 +0000436 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000437 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000438 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700439 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000440 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700441 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000442 return;
443 }
444 session = it->second;
445 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000446
Steven Moreland1b304292021-07-15 22:59:34 +0000447 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700448 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000449 "server state must already be initialized");
450 return;
451 }
452
Steven Moreland5802c2b2021-05-12 20:13:04 +0000453 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000454 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000455 }
456
Yifan Hong702115c2021-06-24 15:39:18 -0700457 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000458
Steven Morelanda63ff932021-05-12 00:03:15 +0000459 // avoid strong cycle
460 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000461
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000462 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000463}
464
Steven Moreland2372f9d2021-08-05 15:42:01 -0700465status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000466 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700467 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000468
Yifan Hongb675ffe2021-08-05 16:37:17 -0700469 unique_fd serverFd(TEMP_FAILURE_RETRY(
470 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000471 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700472 int savedErrno = errno;
473 ALOGE("Could not create socket: %s", strerror(savedErrno));
474 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000475 }
476
477 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
478 int savedErrno = errno;
479 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000481 }
482
Yifan Honge96a1f12021-07-13 16:08:28 -0700483 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
484 // the backlog is increased to a large number.
485 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
486 // to 1.
487 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000488 int savedErrno = errno;
489 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000491 }
492
Steven Moreland704fc1a2021-05-04 23:13:14 +0000493 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
494
Steven Moreland2372f9d2021-08-05 15:42:01 -0700495 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700496 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700497 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700498 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700499 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000500}
501
Steven Morelanddd67b942021-07-23 17:15:41 -0700502void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700503 const std::vector<uint8_t>& id = session->mId;
504 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
505 LOG_RPC_DETAIL("Dropping session with address %s",
506 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000507
508 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700509 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000510 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700511 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000512 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700513 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000514 (void)mSessions.erase(it);
515}
516
Steven Moreland19fc9f72021-06-10 03:57:30 +0000517void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000518 mShutdownCv.notify_all();
519}
520
Yifan Hong0eb5a672021-05-12 18:00:25 -0700521bool RpcServer::hasServer() {
522 std::lock_guard<std::mutex> _l(mLock);
523 return mServer.ok();
524}
525
Yifan Hong00aeb762021-05-12 17:07:36 -0700526unique_fd RpcServer::releaseServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700527 std::lock_guard<std::mutex> _l(mLock);
528 return std::move(mServer);
529}
530
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700532 std::lock_guard<std::mutex> _l(mLock);
533 if (mServer.ok()) {
534 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700535 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700536 }
537 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700538 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700539}
540
Steven Moreland5553ac42020-11-11 02:14:45 +0000541} // namespace android