blob: a0c508be0378afe5a7f3064fe91d49ca5c5f48ae [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 Hong702115c2021-06-24 15:39:18 -070042RpcServer::RpcServer(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
43 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070044RpcServer::~RpcServer() {
45 (void)shutdown();
46}
Steven Moreland5553ac42020-11-11 02:14:45 +000047
Yifan Hong702115c2021-06-24 15:39:18 -070048sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
49 // Default is without TLS.
50 if (rpcTransportCtxFactory == nullptr)
51 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
52 return sp<RpcServer>::make(std::move(rpcTransportCtxFactory));
Steven Moreland5553ac42020-11-11 02:14:45 +000053}
54
55void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
56 mAgreedExperimental = true;
57}
58
Steven Moreland2372f9d2021-08-05 15:42:01 -070059status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000060 return setupSocketServer(UnixSocketAddress(path));
61}
62
Steven Moreland2372f9d2021-08-05 15:42:01 -070063status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000064 // realizing value w/ this type at compile time to avoid ubsan abort
65 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
66
67 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
68}
69
Steven Moreland2372f9d2021-08-05 15:42:01 -070070status_t RpcServer::setupInetServer(const char* address, unsigned int port,
71 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000072 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000073 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070074 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000075 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000076 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070077 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000078 continue;
79 }
80
81 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
82 sockaddr_in addr{};
83 socklen_t len = sizeof(addr);
84 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
85 int savedErrno = errno;
86 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
87 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070088 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000089 }
90 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
91 static_cast<size_t>(len), sizeof(addr));
92 unsigned int realPort = ntohs(addr.sin_port);
93 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
94 "Requesting inet server on %s but it is set up on %u.",
95 socketAddress.toString().c_str(), realPort);
96
97 if (assignedPort != nullptr) {
98 *assignedPort = realPort;
99 }
100
Steven Moreland2372f9d2021-08-05 15:42:01 -0700101 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000102 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000103 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 +0000104 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700105 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000106}
107
Steven Morelandf137de92021-04-24 01:54:26 +0000108void RpcServer::setMaxThreads(size_t threads) {
109 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700110 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000111 mMaxThreads = threads;
112}
113
114size_t RpcServer::getMaxThreads() {
115 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000116}
117
Steven Morelandbf57bce2021-07-26 15:26:12 -0700118void RpcServer::setProtocolVersion(uint32_t version) {
119 mProtocolVersion = version;
120}
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000123 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700124 mRootObjectWeak = mRootObject = binder;
125}
126
127void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
128 std::lock_guard<std::mutex> _l(mLock);
129 mRootObject.clear();
130 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000131}
132
133sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000134 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700135 bool hasWeak = mRootObjectWeak.unsafe_get();
136 sp<IBinder> ret = mRootObjectWeak.promote();
137 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
138 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000139}
140
Yifan Hong326afd12021-05-19 15:24:54 -0700141static void joinRpcServer(sp<RpcServer>&& thiz) {
142 thiz->join();
143}
144
145void RpcServer::start() {
146 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
147 std::lock_guard<std::mutex> _l(mLock);
148 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
149 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
150}
151
Steven Moreland611d15f2021-05-01 01:28:27 +0000152void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700153 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
154
155 {
156 std::lock_guard<std::mutex> _l(mLock);
157 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
158 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
159 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700160 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700161 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Yifan Hong702115c2021-06-24 15:39:18 -0700162
163 mCtx = mRpcTransportCtxFactory->newServerCtx();
164 LOG_ALWAYS_FATAL_IF(mCtx == nullptr, "Unable to create RpcTransportCtx with %s sockets",
165 mRpcTransportCtxFactory->toCString());
Steven Morelandd539fbf2021-05-05 23:40:25 +0000166 }
Yifan Hong1a235852021-05-13 16:07:47 -0700167
Steven Moreland2b4f3802021-05-22 01:46:27 +0000168 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000169 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000170 unique_fd clientFd(TEMP_FAILURE_RETRY(
Yifan Hongb675ffe2021-08-05 16:37:17 -0700171 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC | SOCK_NONBLOCK)));
Steven Moreland410325a2021-06-02 18:37:42 +0000172
173 if (clientFd < 0) {
174 ALOGE("Could not accept4 socket: %s", strerror(errno));
175 continue;
176 }
177 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
178
179 {
180 std::lock_guard<std::mutex> _l(mLock);
181 std::thread thread =
182 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
183 std::move(clientFd));
184 mConnectingThreads[thread.get_id()] = std::move(thread);
185 }
Yifan Hong1a235852021-05-13 16:07:47 -0700186 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000187 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700188
189 {
190 std::lock_guard<std::mutex> _l(mLock);
191 mJoinThreadRunning = false;
192 }
193 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000194}
195
Yifan Hong1a235852021-05-13 16:07:47 -0700196bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700197 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000198 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000199 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000200 return false;
201 }
Yifan Hong1a235852021-05-13 16:07:47 -0700202
203 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000204 for (auto& [id, session] : mSessions) {
205 (void)id;
206 session->mShutdownTrigger->trigger();
207 }
208
Steven Morelandee3f4662021-05-22 01:07:33 +0000209 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000210 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
211 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
212 "Connecting threads: "
213 "%zu, Sessions: %zu. Is your server deadlocked?",
214 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
215 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000216 }
Yifan Hong1a235852021-05-13 16:07:47 -0700217
Yifan Hong326afd12021-05-19 15:24:54 -0700218 // At this point, we know join() is about to exit, but the thread that calls
219 // join() may not have exited yet.
220 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
221 // otherwise ~thread() may call std::terminate(), which may crash the process.
222 // If RpcServer does not own the join thread (aka join() is called directly),
223 // then the owner of RpcServer is responsible for cleaning up that thread.
224 if (mJoinThread.get()) {
225 mJoinThread->join();
226 mJoinThread.reset();
227 }
228
Steven Moreland1c943ec2021-07-13 23:57:56 +0000229 LOG_RPC_DETAIL("Finished waiting on shutdown.");
230
Yifan Hong1a235852021-05-13 16:07:47 -0700231 mShutdownTrigger = nullptr;
Yifan Hong702115c2021-06-24 15:39:18 -0700232 mCtx = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700233 return true;
234}
235
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000237 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000238 std::vector<sp<RpcSession>> sessions;
239 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000240 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000242 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000243 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000244}
245
Steven Morelandd539fbf2021-05-05 23:40:25 +0000246size_t RpcServer::numUninitializedSessions() {
247 std::lock_guard<std::mutex> _l(mLock);
248 return mConnectingThreads.size();
249}
250
Steven Morelanda63ff932021-05-12 00:03:15 +0000251void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000252 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700253 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000254
255 // mShutdownTrigger can only be cleared once connection threads have joined.
256 // It must be set before this thread is started
257 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700258 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
259
260 status_t status = OK;
261
262 int clientFdForLog = clientFd.get();
263 auto client = server->mCtx->newTransport(std::move(clientFd));
264 if (client == nullptr) {
265 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
266 status = DEAD_OBJECT;
267 // still need to cleanup before we can return
268 } else {
269 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
270 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000271
Steven Moreland659416d2021-05-11 00:47:50 +0000272 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700273 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700274 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
275 sizeof(header));
Yifan Hong702115c2021-06-24 15:39:18 -0700276 if (status != OK) {
277 ALOGE("Failed to read ID for client connecting to RPC server: %s",
278 statusToString(status).c_str());
279 // still need to cleanup before we can return
280 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000281 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700282
283 bool incoming = false;
284 uint32_t protocolVersion = 0;
285 RpcAddress sessionId = RpcAddress::zero();
286 bool requestingNewSession = false;
287
288 if (status == OK) {
289 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
290 protocolVersion = std::min(header.version,
291 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
292 sessionId = RpcAddress::fromRawEmbedded(&header.sessionId);
293 requestingNewSession = sessionId.isZero();
294
295 if (requestingNewSession) {
296 RpcNewSessionResponse response{
297 .version = protocolVersion,
298 };
299
Yifan Hong8c950422021-08-05 17:13:55 -0700300 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
301 sizeof(response));
Steven Morelandbf57bce2021-07-26 15:26:12 -0700302 if (status != OK) {
303 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
304 // still need to cleanup before we can return
305 }
306 }
307 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000308
309 std::thread thisThread;
310 sp<RpcSession> session;
311 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000312 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000313
Yifan Hongb3005502021-05-19 15:37:00 -0700314 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
315 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000316 "Must establish connection on owned thread");
317 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000318 ScopeGuard detachGuard = [&]() {
319 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000320 _l.unlock();
321 server->mShutdownCv.notify_all();
322 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000323 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000324
Steven Morelandbf57bce2021-07-26 15:26:12 -0700325 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000326 return;
327 }
328
Steven Morelandbf57bce2021-07-26 15:26:12 -0700329 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000330 if (incoming) {
331 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000332 return;
333 }
334
Steven Moreland01a6bad2021-06-11 00:59:20 +0000335 size_t tries = 0;
336 do {
337 // don't block if there is some entropy issue
338 if (tries++ > 5) {
339 ALOGE("Cannot find new address: %s", sessionId.toString().c_str());
340 return;
341 }
342
343 sessionId = RpcAddress::random(true /*forServer*/);
344 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000345
346 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000347 session->setMaxThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700348 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000349 if (!session->setForServer(server,
350 sp<RpcServer::EventListener>::fromExisting(
351 static_cast<RpcServer::EventListener*>(
352 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000353 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000354 ALOGE("Failed to attach server to session");
355 return;
356 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000357
Steven Moreland01a6bad2021-06-11 00:59:20 +0000358 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000359 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000360 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700361 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000362 ALOGE("Cannot add thread, no record of session with ID %s",
363 sessionId.toString().c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000364 return;
365 }
366 session = it->second;
367 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000368
Steven Moreland1b304292021-07-15 22:59:34 +0000369 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700370 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000371 "server state must already be initialized");
372 return;
373 }
374
Steven Moreland5802c2b2021-05-12 20:13:04 +0000375 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000376 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000377 }
378
Yifan Hong702115c2021-06-24 15:39:18 -0700379 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000380
Steven Morelanda63ff932021-05-12 00:03:15 +0000381 // avoid strong cycle
382 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000383
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000384 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000385}
386
Steven Moreland2372f9d2021-08-05 15:42:01 -0700387status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000388 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700389 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000390
Yifan Hongb675ffe2021-08-05 16:37:17 -0700391 unique_fd serverFd(TEMP_FAILURE_RETRY(
392 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000393 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700394 int savedErrno = errno;
395 ALOGE("Could not create socket: %s", strerror(savedErrno));
396 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000397 }
398
399 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
400 int savedErrno = errno;
401 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700402 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000403 }
404
Yifan Honge96a1f12021-07-13 16:08:28 -0700405 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
406 // the backlog is increased to a large number.
407 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
408 // to 1.
409 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000410 int savedErrno = errno;
411 ALOGE("Could not listen 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
Steven Moreland704fc1a2021-05-04 23:13:14 +0000415 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
416
Steven Moreland2372f9d2021-08-05 15:42:01 -0700417 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700418 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700419 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700420 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700421 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000422}
423
Steven Morelanddd67b942021-07-23 17:15:41 -0700424void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Morelandee78e762021-05-05 21:12:51 +0000425 auto id = session->mId;
426 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
Steven Moreland01a6bad2021-06-11 00:59:20 +0000427 LOG_RPC_DETAIL("Dropping session with address %s", id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000428
429 std::lock_guard<std::mutex> _l(mLock);
430 auto it = mSessions.find(*id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000431 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
432 id->toString().c_str());
433 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
434 id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000435 (void)mSessions.erase(it);
436}
437
Steven Moreland19fc9f72021-06-10 03:57:30 +0000438void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000439 mShutdownCv.notify_all();
440}
441
Yifan Hong0eb5a672021-05-12 18:00:25 -0700442bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700443 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700444 std::lock_guard<std::mutex> _l(mLock);
445 return mServer.ok();
446}
447
Yifan Hong00aeb762021-05-12 17:07:36 -0700448unique_fd RpcServer::releaseServer() {
449 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
450 std::lock_guard<std::mutex> _l(mLock);
451 return std::move(mServer);
452}
453
Steven Moreland2372f9d2021-08-05 15:42:01 -0700454status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700455 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
456 std::lock_guard<std::mutex> _l(mLock);
457 if (mServer.ok()) {
458 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700459 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700460 }
461 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700462 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700463}
464
Steven Moreland5553ac42020-11-11 02:14:45 +0000465} // namespace android