blob: ad9ba9660faece76d1a34041623dcfcff157cf9a [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 Moreland798e0d12021-07-14 23:19:25 +000019#include <poll.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <sys/socket.h>
21#include <sys/un.h>
22
Steven Morelandf137de92021-04-24 01:54:26 +000023#include <thread>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <vector>
25
Steven Moreland5802c2b2021-05-12 20:13:04 +000026#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/Parcel.h>
28#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070029#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <log/log.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000031
Yifan Hong8c950422021-08-05 17:13:55 -070032#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000033#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070034#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000035#include "RpcWireFormat.h"
36
37namespace android {
38
Steven Moreland5802c2b2021-05-12 20:13:04 +000039using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000040using base::unique_fd;
41
Yifan Hongecf937d2021-08-11 17:29:28 -070042RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070043RpcServer::~RpcServer() {
44 (void)shutdown();
45}
Steven Moreland5553ac42020-11-11 02:14:45 +000046
Yifan Hong702115c2021-06-24 15:39:18 -070047sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
48 // Default is without TLS.
49 if (rpcTransportCtxFactory == nullptr)
50 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070051 auto ctx = rpcTransportCtxFactory->newServerCtx();
52 if (ctx == nullptr) return nullptr;
53 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000054}
55
56void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
57 mAgreedExperimental = true;
58}
59
Steven Moreland2372f9d2021-08-05 15:42:01 -070060status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000061 return setupSocketServer(UnixSocketAddress(path));
62}
63
Steven Moreland2372f9d2021-08-05 15:42:01 -070064status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000065 // realizing value w/ this type at compile time to avoid ubsan abort
66 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
67
68 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
69}
70
Steven Moreland2372f9d2021-08-05 15:42:01 -070071status_t RpcServer::setupInetServer(const char* address, unsigned int port,
72 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000073 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000074 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070075 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000076 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000077 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070078 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000079 continue;
80 }
81
82 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
83 sockaddr_in addr{};
84 socklen_t len = sizeof(addr);
85 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
86 int savedErrno = errno;
87 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
88 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070089 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000090 }
91 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
92 static_cast<size_t>(len), sizeof(addr));
93 unsigned int realPort = ntohs(addr.sin_port);
94 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
95 "Requesting inet server on %s but it is set up on %u.",
96 socketAddress.toString().c_str(), realPort);
97
98 if (assignedPort != nullptr) {
99 *assignedPort = realPort;
100 }
101
Steven Moreland2372f9d2021-08-05 15:42:01 -0700102 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000103 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000104 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 +0000105 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700106 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000107}
108
Steven Morelandf137de92021-04-24 01:54:26 +0000109void RpcServer::setMaxThreads(size_t threads) {
110 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700111 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000112 mMaxThreads = threads;
113}
114
115size_t RpcServer::getMaxThreads() {
116 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000117}
118
Steven Morelandbf57bce2021-07-26 15:26:12 -0700119void RpcServer::setProtocolVersion(uint32_t version) {
120 mProtocolVersion = version;
121}
122
Steven Moreland5553ac42020-11-11 02:14:45 +0000123void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000124 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700125 mRootObjectWeak = mRootObject = binder;
126}
127
128void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
129 std::lock_guard<std::mutex> _l(mLock);
130 mRootObject.clear();
131 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000132}
133
134sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000135 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700136 bool hasWeak = mRootObjectWeak.unsafe_get();
137 sp<IBinder> ret = mRootObjectWeak.promote();
138 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
139 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140}
141
Yifan Hongecf937d2021-08-11 17:29:28 -0700142std::string RpcServer::getCertificate(CertificateFormat format) {
143 std::lock_guard<std::mutex> _l(mLock);
144 return mCtx->getCertificate(format);
145}
146
147status_t RpcServer::addTrustedPeerCertificate(CertificateFormat format, std::string_view cert) {
148 std::lock_guard<std::mutex> _l(mLock);
149 // Ensure that join thread is not running or shutdown trigger is not set up. In either case,
150 // it means there are child threads running. It is invalid to add trusted peer certificates
151 // after join thread and/or child threads are running to avoid race condition.
152 if (mJoinThreadRunning || mShutdownTrigger != nullptr) return INVALID_OPERATION;
153 return mCtx->addTrustedPeerCertificate(format, cert);
154}
155
Yifan Hong326afd12021-05-19 15:24:54 -0700156static void joinRpcServer(sp<RpcServer>&& thiz) {
157 thiz->join();
158}
159
160void RpcServer::start() {
161 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
162 std::lock_guard<std::mutex> _l(mLock);
163 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
164 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
165}
166
Steven Moreland611d15f2021-05-01 01:28:27 +0000167void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700168 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
169
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) {
Steven Moreland410325a2021-06-02 18:37:42 +0000181 unique_fd clientFd(TEMP_FAILURE_RETRY(
Yifan Hongb675ffe2021-08-05 16:37:17 -0700182 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC | SOCK_NONBLOCK)));
Steven Moreland410325a2021-06-02 18:37:42 +0000183
184 if (clientFd < 0) {
185 ALOGE("Could not accept4 socket: %s", strerror(errno));
186 continue;
187 }
188 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
189
190 {
191 std::lock_guard<std::mutex> _l(mLock);
192 std::thread thread =
193 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
194 std::move(clientFd));
195 mConnectingThreads[thread.get_id()] = std::move(thread);
196 }
Yifan Hong1a235852021-05-13 16:07:47 -0700197 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000198 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700199
200 {
201 std::lock_guard<std::mutex> _l(mLock);
202 mJoinThreadRunning = false;
203 }
204 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000205}
206
Yifan Hong1a235852021-05-13 16:07:47 -0700207bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700208 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000209 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000210 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000211 return false;
212 }
Yifan Hong1a235852021-05-13 16:07:47 -0700213
214 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000215 for (auto& [id, session] : mSessions) {
216 (void)id;
217 session->mShutdownTrigger->trigger();
218 }
219
Steven Morelandee3f4662021-05-22 01:07:33 +0000220 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000221 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
222 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
223 "Connecting threads: "
224 "%zu, Sessions: %zu. Is your server deadlocked?",
225 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
226 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000227 }
Yifan Hong1a235852021-05-13 16:07:47 -0700228
Yifan Hong326afd12021-05-19 15:24:54 -0700229 // At this point, we know join() is about to exit, but the thread that calls
230 // join() may not have exited yet.
231 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
232 // otherwise ~thread() may call std::terminate(), which may crash the process.
233 // If RpcServer does not own the join thread (aka join() is called directly),
234 // then the owner of RpcServer is responsible for cleaning up that thread.
235 if (mJoinThread.get()) {
236 mJoinThread->join();
237 mJoinThread.reset();
238 }
239
Steven Moreland1c943ec2021-07-13 23:57:56 +0000240 LOG_RPC_DETAIL("Finished waiting on shutdown.");
241
Yifan Hong1a235852021-05-13 16:07:47 -0700242 mShutdownTrigger = nullptr;
243 return true;
244}
245
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000246std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000247 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000248 std::vector<sp<RpcSession>> sessions;
249 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000250 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000252 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000254}
255
Steven Morelandd539fbf2021-05-05 23:40:25 +0000256size_t RpcServer::numUninitializedSessions() {
257 std::lock_guard<std::mutex> _l(mLock);
258 return mConnectingThreads.size();
259}
260
Steven Morelanda63ff932021-05-12 00:03:15 +0000261void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000262 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700263 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000264
265 // mShutdownTrigger can only be cleared once connection threads have joined.
266 // It must be set before this thread is started
267 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700268 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
269
270 status_t status = OK;
271
272 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700273 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700274 if (client == nullptr) {
275 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
276 status = DEAD_OBJECT;
277 // still need to cleanup before we can return
278 } else {
279 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
280 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000281
Steven Moreland659416d2021-05-11 00:47:50 +0000282 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700283 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700284 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
285 sizeof(header));
Yifan Hong702115c2021-06-24 15:39:18 -0700286 if (status != OK) {
287 ALOGE("Failed to read ID for client connecting to RPC server: %s",
288 statusToString(status).c_str());
289 // still need to cleanup before we can return
290 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000291 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700292
293 bool incoming = false;
294 uint32_t protocolVersion = 0;
295 RpcAddress sessionId = RpcAddress::zero();
296 bool requestingNewSession = false;
297
298 if (status == OK) {
299 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
300 protocolVersion = std::min(header.version,
301 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
302 sessionId = RpcAddress::fromRawEmbedded(&header.sessionId);
303 requestingNewSession = sessionId.isZero();
304
305 if (requestingNewSession) {
306 RpcNewSessionResponse response{
307 .version = protocolVersion,
308 };
309
Yifan Hong8c950422021-08-05 17:13:55 -0700310 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
311 sizeof(response));
Steven Morelandbf57bce2021-07-26 15:26:12 -0700312 if (status != OK) {
313 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
314 // still need to cleanup before we can return
315 }
316 }
317 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000318
319 std::thread thisThread;
320 sp<RpcSession> session;
321 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000322 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000323
Yifan Hongb3005502021-05-19 15:37:00 -0700324 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
325 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000326 "Must establish connection on owned thread");
327 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000328 ScopeGuard detachGuard = [&]() {
329 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000330 _l.unlock();
331 server->mShutdownCv.notify_all();
332 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000333 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000334
Steven Morelandbf57bce2021-07-26 15:26:12 -0700335 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000336 return;
337 }
338
Steven Morelandbf57bce2021-07-26 15:26:12 -0700339 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000340 if (incoming) {
341 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000342 return;
343 }
344
Steven Moreland01a6bad2021-06-11 00:59:20 +0000345 size_t tries = 0;
346 do {
347 // don't block if there is some entropy issue
348 if (tries++ > 5) {
349 ALOGE("Cannot find new address: %s", sessionId.toString().c_str());
350 return;
351 }
352
353 sessionId = RpcAddress::random(true /*forServer*/);
354 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000355
356 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000357 session->setMaxThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700358 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000359 if (!session->setForServer(server,
360 sp<RpcServer::EventListener>::fromExisting(
361 static_cast<RpcServer::EventListener*>(
362 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000363 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000364 ALOGE("Failed to attach server to session");
365 return;
366 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000367
Steven Moreland01a6bad2021-06-11 00:59:20 +0000368 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000369 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000370 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700371 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000372 ALOGE("Cannot add thread, no record of session with ID %s",
373 sessionId.toString().c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000374 return;
375 }
376 session = it->second;
377 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000378
Steven Moreland1b304292021-07-15 22:59:34 +0000379 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700380 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000381 "server state must already be initialized");
382 return;
383 }
384
Steven Moreland5802c2b2021-05-12 20:13:04 +0000385 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000386 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000387 }
388
Yifan Hong702115c2021-06-24 15:39:18 -0700389 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000390
Steven Morelanda63ff932021-05-12 00:03:15 +0000391 // avoid strong cycle
392 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000393
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000394 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000395}
396
Steven Moreland2372f9d2021-08-05 15:42:01 -0700397status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000398 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700399 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000400
Yifan Hongb675ffe2021-08-05 16:37:17 -0700401 unique_fd serverFd(TEMP_FAILURE_RETRY(
402 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000403 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700404 int savedErrno = errno;
405 ALOGE("Could not create socket: %s", strerror(savedErrno));
406 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000407 }
408
409 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
410 int savedErrno = errno;
411 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700412 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000413 }
414
Yifan Honge96a1f12021-07-13 16:08:28 -0700415 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
416 // the backlog is increased to a large number.
417 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
418 // to 1.
419 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000420 int savedErrno = errno;
421 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700422 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000423 }
424
Steven Moreland704fc1a2021-05-04 23:13:14 +0000425 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
426
Steven Moreland2372f9d2021-08-05 15:42:01 -0700427 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700428 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700429 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700430 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700431 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000432}
433
Steven Morelanddd67b942021-07-23 17:15:41 -0700434void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Morelandee78e762021-05-05 21:12:51 +0000435 auto id = session->mId;
436 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
Steven Moreland01a6bad2021-06-11 00:59:20 +0000437 LOG_RPC_DETAIL("Dropping session with address %s", id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000438
439 std::lock_guard<std::mutex> _l(mLock);
440 auto it = mSessions.find(*id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000441 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
442 id->toString().c_str());
443 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
444 id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000445 (void)mSessions.erase(it);
446}
447
Steven Moreland19fc9f72021-06-10 03:57:30 +0000448void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000449 mShutdownCv.notify_all();
450}
451
Yifan Hong0eb5a672021-05-12 18:00:25 -0700452bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700453 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700454 std::lock_guard<std::mutex> _l(mLock);
455 return mServer.ok();
456}
457
Yifan Hong00aeb762021-05-12 17:07:36 -0700458unique_fd RpcServer::releaseServer() {
459 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
460 std::lock_guard<std::mutex> _l(mLock);
461 return std::move(mServer);
462}
463
Steven Moreland2372f9d2021-08-05 15:42:01 -0700464status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700465 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
466 std::lock_guard<std::mutex> _l(mLock);
467 if (mServer.ok()) {
468 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700469 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700470 }
471 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700472 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700473}
474
Steven Moreland5553ac42020-11-11 02:14:45 +0000475} // namespace android