blob: 4fa99c0e45184326de4320c0ebac695e4a0145c0 [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
Steven Moreland611d15f2021-05-01 01:28:27 +000032#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070033#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include "RpcWireFormat.h"
35
36namespace android {
37
Steven Moreland5802c2b2021-05-12 20:13:04 +000038using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000039using base::unique_fd;
40
Yifan Hong702115c2021-06-24 15:39:18 -070041RpcServer::RpcServer(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
42 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {}
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();
51 return sp<RpcServer>::make(std::move(rpcTransportCtxFactory));
Steven Moreland5553ac42020-11-11 02:14:45 +000052}
53
54void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
55 mAgreedExperimental = true;
56}
57
Steven Moreland2372f9d2021-08-05 15:42:01 -070058status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000059 return setupSocketServer(UnixSocketAddress(path));
60}
61
Steven Moreland2372f9d2021-08-05 15:42:01 -070062status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000063 // realizing value w/ this type at compile time to avoid ubsan abort
64 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
65
66 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
67}
68
Steven Moreland2372f9d2021-08-05 15:42:01 -070069status_t RpcServer::setupInetServer(const char* address, unsigned int port,
70 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000071 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000072 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070073 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000074 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000075 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070076 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000077 continue;
78 }
79
80 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
81 sockaddr_in addr{};
82 socklen_t len = sizeof(addr);
83 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
84 int savedErrno = errno;
85 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
86 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070087 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000088 }
89 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
90 static_cast<size_t>(len), sizeof(addr));
91 unsigned int realPort = ntohs(addr.sin_port);
92 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
93 "Requesting inet server on %s but it is set up on %u.",
94 socketAddress.toString().c_str(), realPort);
95
96 if (assignedPort != nullptr) {
97 *assignedPort = realPort;
98 }
99
Steven Moreland2372f9d2021-08-05 15:42:01 -0700100 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000101 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000102 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 +0000103 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700104 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000105}
106
Steven Morelandf137de92021-04-24 01:54:26 +0000107void RpcServer::setMaxThreads(size_t threads) {
108 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700109 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000110 mMaxThreads = threads;
111}
112
113size_t RpcServer::getMaxThreads() {
114 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000115}
116
Steven Morelandbf57bce2021-07-26 15:26:12 -0700117void RpcServer::setProtocolVersion(uint32_t version) {
118 mProtocolVersion = version;
119}
120
Steven Moreland5553ac42020-11-11 02:14:45 +0000121void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000122 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700123 mRootObjectWeak = mRootObject = binder;
124}
125
126void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
127 std::lock_guard<std::mutex> _l(mLock);
128 mRootObject.clear();
129 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000130}
131
132sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000133 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700134 bool hasWeak = mRootObjectWeak.unsafe_get();
135 sp<IBinder> ret = mRootObjectWeak.promote();
136 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
137 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000138}
139
Yifan Hong326afd12021-05-19 15:24:54 -0700140static void joinRpcServer(sp<RpcServer>&& thiz) {
141 thiz->join();
142}
143
144void RpcServer::start() {
145 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
146 std::lock_guard<std::mutex> _l(mLock);
147 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
148 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
149}
150
Steven Moreland611d15f2021-05-01 01:28:27 +0000151void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700152 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
153
154 {
155 std::lock_guard<std::mutex> _l(mLock);
156 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
157 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
158 mJoinThreadRunning = true;
Steven Morelande47511f2021-05-20 00:07:41 +0000159 mShutdownTrigger = RpcSession::FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700160 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Yifan Hong702115c2021-06-24 15:39:18 -0700161
162 mCtx = mRpcTransportCtxFactory->newServerCtx();
163 LOG_ALWAYS_FATAL_IF(mCtx == nullptr, "Unable to create RpcTransportCtx with %s sockets",
164 mRpcTransportCtxFactory->toCString());
Steven Morelandd539fbf2021-05-05 23:40:25 +0000165 }
Yifan Hong1a235852021-05-13 16:07:47 -0700166
Steven Moreland2b4f3802021-05-22 01:46:27 +0000167 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000168 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000169 unique_fd clientFd(TEMP_FAILURE_RETRY(
170 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
171
172 if (clientFd < 0) {
173 ALOGE("Could not accept4 socket: %s", strerror(errno));
174 continue;
175 }
176 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
177
178 {
179 std::lock_guard<std::mutex> _l(mLock);
180 std::thread thread =
181 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
182 std::move(clientFd));
183 mConnectingThreads[thread.get_id()] = std::move(thread);
184 }
Yifan Hong1a235852021-05-13 16:07:47 -0700185 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000186 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700187
188 {
189 std::lock_guard<std::mutex> _l(mLock);
190 mJoinThreadRunning = false;
191 }
192 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000193}
194
Yifan Hong1a235852021-05-13 16:07:47 -0700195bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700196 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000197 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000198 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000199 return false;
200 }
Yifan Hong1a235852021-05-13 16:07:47 -0700201
202 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000203 for (auto& [id, session] : mSessions) {
204 (void)id;
205 session->mShutdownTrigger->trigger();
206 }
207
Steven Morelandee3f4662021-05-22 01:07:33 +0000208 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000209 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
210 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
211 "Connecting threads: "
212 "%zu, Sessions: %zu. Is your server deadlocked?",
213 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
214 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000215 }
Yifan Hong1a235852021-05-13 16:07:47 -0700216
Yifan Hong326afd12021-05-19 15:24:54 -0700217 // At this point, we know join() is about to exit, but the thread that calls
218 // join() may not have exited yet.
219 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
220 // otherwise ~thread() may call std::terminate(), which may crash the process.
221 // If RpcServer does not own the join thread (aka join() is called directly),
222 // then the owner of RpcServer is responsible for cleaning up that thread.
223 if (mJoinThread.get()) {
224 mJoinThread->join();
225 mJoinThread.reset();
226 }
227
Steven Moreland1c943ec2021-07-13 23:57:56 +0000228 LOG_RPC_DETAIL("Finished waiting on shutdown.");
229
Yifan Hong1a235852021-05-13 16:07:47 -0700230 mShutdownTrigger = nullptr;
Yifan Hong702115c2021-06-24 15:39:18 -0700231 mCtx = nullptr;
Yifan Hong1a235852021-05-13 16:07:47 -0700232 return true;
233}
234
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000235std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000236 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000237 std::vector<sp<RpcSession>> sessions;
238 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000239 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000241 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000243}
244
Steven Morelandd539fbf2021-05-05 23:40:25 +0000245size_t RpcServer::numUninitializedSessions() {
246 std::lock_guard<std::mutex> _l(mLock);
247 return mConnectingThreads.size();
248}
249
Steven Morelanda63ff932021-05-12 00:03:15 +0000250void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000251 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700252 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000253
254 // mShutdownTrigger can only be cleared once connection threads have joined.
255 // It must be set before this thread is started
256 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700257 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
258
259 status_t status = OK;
260
261 int clientFdForLog = clientFd.get();
262 auto client = server->mCtx->newTransport(std::move(clientFd));
263 if (client == nullptr) {
264 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
265 status = DEAD_OBJECT;
266 // still need to cleanup before we can return
267 } else {
268 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
269 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000270
Steven Moreland659416d2021-05-11 00:47:50 +0000271 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700272 if (status == OK) {
273 status = server->mShutdownTrigger->interruptableReadFully(client.get(), &header,
274 sizeof(header));
275 if (status != OK) {
276 ALOGE("Failed to read ID for client connecting to RPC server: %s",
277 statusToString(status).c_str());
278 // still need to cleanup before we can return
279 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000280 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700281
282 bool incoming = false;
283 uint32_t protocolVersion = 0;
284 RpcAddress sessionId = RpcAddress::zero();
285 bool requestingNewSession = false;
286
287 if (status == OK) {
288 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
289 protocolVersion = std::min(header.version,
290 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
291 sessionId = RpcAddress::fromRawEmbedded(&header.sessionId);
292 requestingNewSession = sessionId.isZero();
293
294 if (requestingNewSession) {
295 RpcNewSessionResponse response{
296 .version = protocolVersion,
297 };
298
Yifan Hong702115c2021-06-24 15:39:18 -0700299 status = server->mShutdownTrigger->interruptableWriteFully(client.get(), &response,
Steven Morelandbf57bce2021-07-26 15:26:12 -0700300 sizeof(response));
301 if (status != OK) {
302 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
303 // still need to cleanup before we can return
304 }
305 }
306 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000307
308 std::thread thisThread;
309 sp<RpcSession> session;
310 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000311 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000312
Yifan Hongb3005502021-05-19 15:37:00 -0700313 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
314 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000315 "Must establish connection on owned thread");
316 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000317 ScopeGuard detachGuard = [&]() {
318 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000319 _l.unlock();
320 server->mShutdownCv.notify_all();
321 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000322 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000323
Steven Morelandbf57bce2021-07-26 15:26:12 -0700324 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000325 return;
326 }
327
Steven Morelandbf57bce2021-07-26 15:26:12 -0700328 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000329 if (incoming) {
330 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000331 return;
332 }
333
Steven Moreland01a6bad2021-06-11 00:59:20 +0000334 size_t tries = 0;
335 do {
336 // don't block if there is some entropy issue
337 if (tries++ > 5) {
338 ALOGE("Cannot find new address: %s", sessionId.toString().c_str());
339 return;
340 }
341
342 sessionId = RpcAddress::random(true /*forServer*/);
343 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000344
345 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000346 session->setMaxThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700347 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000348 if (!session->setForServer(server,
349 sp<RpcServer::EventListener>::fromExisting(
350 static_cast<RpcServer::EventListener*>(
351 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000352 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000353 ALOGE("Failed to attach server to session");
354 return;
355 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000356
Steven Moreland01a6bad2021-06-11 00:59:20 +0000357 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000358 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000359 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700360 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000361 ALOGE("Cannot add thread, no record of session with ID %s",
362 sessionId.toString().c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000363 return;
364 }
365 session = it->second;
366 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000367
Steven Moreland1b304292021-07-15 22:59:34 +0000368 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700369 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000370 "server state must already be initialized");
371 return;
372 }
373
Steven Moreland5802c2b2021-05-12 20:13:04 +0000374 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000375 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000376 }
377
Yifan Hong702115c2021-06-24 15:39:18 -0700378 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000379
Steven Morelanda63ff932021-05-12 00:03:15 +0000380 // avoid strong cycle
381 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000382
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000383 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000384}
385
Steven Moreland2372f9d2021-08-05 15:42:01 -0700386status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000387 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700388 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000389
390 unique_fd serverFd(
391 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
392 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700393 int savedErrno = errno;
394 ALOGE("Could not create socket: %s", strerror(savedErrno));
395 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000396 }
397
398 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
399 int savedErrno = errno;
400 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700401 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000402 }
403
Yifan Honge96a1f12021-07-13 16:08:28 -0700404 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
405 // the backlog is increased to a large number.
406 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
407 // to 1.
408 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000409 int savedErrno = errno;
410 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700411 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000412 }
413
Steven Moreland704fc1a2021-05-04 23:13:14 +0000414 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
415
Steven Moreland2372f9d2021-08-05 15:42:01 -0700416 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700417 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700418 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700419 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700420 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000421}
422
Steven Morelanddd67b942021-07-23 17:15:41 -0700423void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Morelandee78e762021-05-05 21:12:51 +0000424 auto id = session->mId;
425 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
Steven Moreland01a6bad2021-06-11 00:59:20 +0000426 LOG_RPC_DETAIL("Dropping session with address %s", id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000427
428 std::lock_guard<std::mutex> _l(mLock);
429 auto it = mSessions.find(*id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000430 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
431 id->toString().c_str());
432 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
433 id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000434 (void)mSessions.erase(it);
435}
436
Steven Moreland19fc9f72021-06-10 03:57:30 +0000437void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000438 mShutdownCv.notify_all();
439}
440
Yifan Hong0eb5a672021-05-12 18:00:25 -0700441bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700442 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700443 std::lock_guard<std::mutex> _l(mLock);
444 return mServer.ok();
445}
446
Yifan Hong00aeb762021-05-12 17:07:36 -0700447unique_fd RpcServer::releaseServer() {
448 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
449 std::lock_guard<std::mutex> _l(mLock);
450 return std::move(mServer);
451}
452
Steven Moreland2372f9d2021-08-05 15:42:01 -0700453status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700454 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
455 std::lock_guard<std::mutex> _l(mLock);
456 if (mServer.ok()) {
457 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700458 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700459 }
460 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700461 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700462}
463
Steven Moreland5553ac42020-11-11 02:14:45 +0000464} // namespace android