blob: ba723e6ef3a2fb1f5320c1fe307baa401645ab4c [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
Yifan Hong326afd12021-05-19 15:24:54 -0700147static void joinRpcServer(sp<RpcServer>&& thiz) {
148 thiz->join();
149}
150
151void RpcServer::start() {
152 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
153 std::lock_guard<std::mutex> _l(mLock);
154 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
155 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
156}
157
Steven Moreland611d15f2021-05-01 01:28:27 +0000158void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700159 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
160
161 {
162 std::lock_guard<std::mutex> _l(mLock);
163 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
164 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
165 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700166 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700167 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000168 }
Yifan Hong1a235852021-05-13 16:07:47 -0700169
Steven Moreland2b4f3802021-05-22 01:46:27 +0000170 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000171 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000172 unique_fd clientFd(TEMP_FAILURE_RETRY(
Yifan Hongb675ffe2021-08-05 16:37:17 -0700173 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC | SOCK_NONBLOCK)));
Steven Moreland410325a2021-06-02 18:37:42 +0000174
175 if (clientFd < 0) {
176 ALOGE("Could not accept4 socket: %s", strerror(errno));
177 continue;
178 }
179 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
180
181 {
182 std::lock_guard<std::mutex> _l(mLock);
183 std::thread thread =
184 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
185 std::move(clientFd));
186 mConnectingThreads[thread.get_id()] = std::move(thread);
187 }
Yifan Hong1a235852021-05-13 16:07:47 -0700188 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000189 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700190
191 {
192 std::lock_guard<std::mutex> _l(mLock);
193 mJoinThreadRunning = false;
194 }
195 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000196}
197
Yifan Hong1a235852021-05-13 16:07:47 -0700198bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700199 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000200 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000201 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000202 return false;
203 }
Yifan Hong1a235852021-05-13 16:07:47 -0700204
205 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000206 for (auto& [id, session] : mSessions) {
207 (void)id;
208 session->mShutdownTrigger->trigger();
209 }
210
Steven Morelandee3f4662021-05-22 01:07:33 +0000211 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000212 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
213 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
214 "Connecting threads: "
215 "%zu, Sessions: %zu. Is your server deadlocked?",
216 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
217 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000218 }
Yifan Hong1a235852021-05-13 16:07:47 -0700219
Yifan Hong326afd12021-05-19 15:24:54 -0700220 // At this point, we know join() is about to exit, but the thread that calls
221 // join() may not have exited yet.
222 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
223 // otherwise ~thread() may call std::terminate(), which may crash the process.
224 // If RpcServer does not own the join thread (aka join() is called directly),
225 // then the owner of RpcServer is responsible for cleaning up that thread.
226 if (mJoinThread.get()) {
227 mJoinThread->join();
228 mJoinThread.reset();
229 }
230
Steven Moreland1c943ec2021-07-13 23:57:56 +0000231 LOG_RPC_DETAIL("Finished waiting on shutdown.");
232
Yifan Hong1a235852021-05-13 16:07:47 -0700233 mShutdownTrigger = nullptr;
234 return true;
235}
236
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000237std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000238 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239 std::vector<sp<RpcSession>> sessions;
240 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000241 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000243 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000245}
246
Steven Morelandd539fbf2021-05-05 23:40:25 +0000247size_t RpcServer::numUninitializedSessions() {
248 std::lock_guard<std::mutex> _l(mLock);
249 return mConnectingThreads.size();
250}
251
Steven Morelanda63ff932021-05-12 00:03:15 +0000252void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000253 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700254 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000255
256 // mShutdownTrigger can only be cleared once connection threads have joined.
257 // It must be set before this thread is started
258 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700259 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
260
261 status_t status = OK;
262
263 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700264 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700265 if (client == nullptr) {
266 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
267 status = DEAD_OBJECT;
268 // still need to cleanup before we can return
269 } else {
270 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
271 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000272
Steven Moreland659416d2021-05-11 00:47:50 +0000273 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700274 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700275 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
276 sizeof(header));
Yifan Hong702115c2021-06-24 15:39:18 -0700277 if (status != OK) {
278 ALOGE("Failed to read ID for client connecting to RPC server: %s",
279 statusToString(status).c_str());
280 // still need to cleanup before we can return
281 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000282 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700283
284 bool incoming = false;
285 uint32_t protocolVersion = 0;
286 RpcAddress sessionId = RpcAddress::zero();
287 bool requestingNewSession = false;
288
289 if (status == OK) {
290 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
291 protocolVersion = std::min(header.version,
292 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
293 sessionId = RpcAddress::fromRawEmbedded(&header.sessionId);
294 requestingNewSession = sessionId.isZero();
295
296 if (requestingNewSession) {
297 RpcNewSessionResponse response{
298 .version = protocolVersion,
299 };
300
Yifan Hong8c950422021-08-05 17:13:55 -0700301 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
302 sizeof(response));
Steven Morelandbf57bce2021-07-26 15:26:12 -0700303 if (status != OK) {
304 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
305 // still need to cleanup before we can return
306 }
307 }
308 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000309
310 std::thread thisThread;
311 sp<RpcSession> session;
312 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000313 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000314
Yifan Hongb3005502021-05-19 15:37:00 -0700315 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
316 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000317 "Must establish connection on owned thread");
318 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000319 ScopeGuard detachGuard = [&]() {
320 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000321 _l.unlock();
322 server->mShutdownCv.notify_all();
323 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000324 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000325
Steven Morelandbf57bce2021-07-26 15:26:12 -0700326 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000327 return;
328 }
329
Steven Morelandbf57bce2021-07-26 15:26:12 -0700330 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000331 if (incoming) {
332 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000333 return;
334 }
335
Steven Moreland01a6bad2021-06-11 00:59:20 +0000336 size_t tries = 0;
337 do {
338 // don't block if there is some entropy issue
339 if (tries++ > 5) {
340 ALOGE("Cannot find new address: %s", sessionId.toString().c_str());
341 return;
342 }
343
344 sessionId = RpcAddress::random(true /*forServer*/);
345 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000346
347 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000348 session->setMaxThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700349 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000350 if (!session->setForServer(server,
351 sp<RpcServer::EventListener>::fromExisting(
352 static_cast<RpcServer::EventListener*>(
353 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000354 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000355 ALOGE("Failed to attach server to session");
356 return;
357 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000358
Steven Moreland01a6bad2021-06-11 00:59:20 +0000359 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000360 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000361 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700362 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000363 ALOGE("Cannot add thread, no record of session with ID %s",
364 sessionId.toString().c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000365 return;
366 }
367 session = it->second;
368 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000369
Steven Moreland1b304292021-07-15 22:59:34 +0000370 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700371 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000372 "server state must already be initialized");
373 return;
374 }
375
Steven Moreland5802c2b2021-05-12 20:13:04 +0000376 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000377 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000378 }
379
Yifan Hong702115c2021-06-24 15:39:18 -0700380 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000381
Steven Morelanda63ff932021-05-12 00:03:15 +0000382 // avoid strong cycle
383 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000384
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000385 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000386}
387
Steven Moreland2372f9d2021-08-05 15:42:01 -0700388status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000389 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700390 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000391
Yifan Hongb675ffe2021-08-05 16:37:17 -0700392 unique_fd serverFd(TEMP_FAILURE_RETRY(
393 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000394 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700395 int savedErrno = errno;
396 ALOGE("Could not create socket: %s", strerror(savedErrno));
397 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000398 }
399
400 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
401 int savedErrno = errno;
402 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700403 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000404 }
405
Yifan Honge96a1f12021-07-13 16:08:28 -0700406 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
407 // the backlog is increased to a large number.
408 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
409 // to 1.
410 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000411 int savedErrno = errno;
412 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700413 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000414 }
415
Steven Moreland704fc1a2021-05-04 23:13:14 +0000416 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
417
Steven Moreland2372f9d2021-08-05 15:42:01 -0700418 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700419 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700420 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700421 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700422 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000423}
424
Steven Morelanddd67b942021-07-23 17:15:41 -0700425void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Morelandee78e762021-05-05 21:12:51 +0000426 auto id = session->mId;
427 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
Steven Moreland01a6bad2021-06-11 00:59:20 +0000428 LOG_RPC_DETAIL("Dropping session with address %s", id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000429
430 std::lock_guard<std::mutex> _l(mLock);
431 auto it = mSessions.find(*id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000432 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
433 id->toString().c_str());
434 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
435 id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000436 (void)mSessions.erase(it);
437}
438
Steven Moreland19fc9f72021-06-10 03:57:30 +0000439void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000440 mShutdownCv.notify_all();
441}
442
Yifan Hong0eb5a672021-05-12 18:00:25 -0700443bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700444 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700445 std::lock_guard<std::mutex> _l(mLock);
446 return mServer.ok();
447}
448
Yifan Hong00aeb762021-05-12 17:07:36 -0700449unique_fd RpcServer::releaseServer() {
450 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
451 std::lock_guard<std::mutex> _l(mLock);
452 return std::move(mServer);
453}
454
Steven Moreland2372f9d2021-08-05 15:42:01 -0700455status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700456 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
457 std::lock_guard<std::mutex> _l(mLock);
458 if (mServer.ok()) {
459 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700460 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700461 }
462 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700463 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700464}
465
Steven Moreland5553ac42020-11-11 02:14:45 +0000466} // namespace android