blob: 967b8e380104b64fa7fcd40cf536467b59c77aef [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcServer"
18
Steven Morelandc5032042021-09-30 15:40:27 -070019#include <inttypes.h>
Steven Moreland798e0d12021-07-14 23:19:25 +000020#include <poll.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000021#include <sys/socket.h>
22#include <sys/un.h>
23
Steven Morelandf137de92021-04-24 01:54:26 +000024#include <thread>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <vector>
26
Steven Moreland826367f2021-09-10 14:05:31 -070027#include <android-base/file.h>
28#include <android-base/hex.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000029#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/Parcel.h>
31#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070032#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <log/log.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034
Yifan Hong8c950422021-08-05 17:13:55 -070035#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000036#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070037#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038#include "RpcWireFormat.h"
39
40namespace android {
41
Steven Morelandc5032042021-09-30 15:40:27 -070042constexpr size_t kSessionIdBytes = 32;
43
Steven Moreland5802c2b2021-05-12 20:13:04 +000044using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000045using base::unique_fd;
46
Yifan Hongecf937d2021-08-11 17:29:28 -070047RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070048RpcServer::~RpcServer() {
49 (void)shutdown();
50}
Steven Moreland5553ac42020-11-11 02:14:45 +000051
Yifan Hong702115c2021-06-24 15:39:18 -070052sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
53 // Default is without TLS.
54 if (rpcTransportCtxFactory == nullptr)
55 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070056 auto ctx = rpcTransportCtxFactory->newServerCtx();
57 if (ctx == nullptr) return nullptr;
58 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000059}
60
61void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
62 mAgreedExperimental = true;
63}
64
Steven Moreland2372f9d2021-08-05 15:42:01 -070065status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000066 return setupSocketServer(UnixSocketAddress(path));
67}
68
Steven Moreland2372f9d2021-08-05 15:42:01 -070069status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000070 // realizing value w/ this type at compile time to avoid ubsan abort
71 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
72
73 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
74}
75
Steven Moreland2372f9d2021-08-05 15:42:01 -070076status_t RpcServer::setupInetServer(const char* address, unsigned int port,
77 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000078 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000079 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070080 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000081 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000082 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070083 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000084 continue;
85 }
86
87 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
88 sockaddr_in addr{};
89 socklen_t len = sizeof(addr);
90 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
91 int savedErrno = errno;
92 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
93 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070094 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000095 }
96 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
97 static_cast<size_t>(len), sizeof(addr));
98 unsigned int realPort = ntohs(addr.sin_port);
99 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
100 "Requesting inet server on %s but it is set up on %u.",
101 socketAddress.toString().c_str(), realPort);
102
103 if (assignedPort != nullptr) {
104 *assignedPort = realPort;
105 }
106
Steven Moreland2372f9d2021-08-05 15:42:01 -0700107 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000108 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000109 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 +0000110 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700111 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000112}
113
Steven Morelandf137de92021-04-24 01:54:26 +0000114void RpcServer::setMaxThreads(size_t threads) {
115 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700116 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000117 mMaxThreads = threads;
118}
119
120size_t RpcServer::getMaxThreads() {
121 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000122}
123
Steven Morelandbf57bce2021-07-26 15:26:12 -0700124void RpcServer::setProtocolVersion(uint32_t version) {
125 mProtocolVersion = version;
126}
127
Steven Moreland5553ac42020-11-11 02:14:45 +0000128void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000129 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700130 mRootObjectWeak = mRootObject = binder;
131}
132
133void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
134 std::lock_guard<std::mutex> _l(mLock);
135 mRootObject.clear();
136 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137}
138
139sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000140 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700141 bool hasWeak = mRootObjectWeak.unsafe_get();
142 sp<IBinder> ret = mRootObjectWeak.promote();
143 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
144 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000145}
146
Yifan Hong9734cfc2021-09-13 16:14:09 -0700147std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700148 std::lock_guard<std::mutex> _l(mLock);
149 return mCtx->getCertificate(format);
150}
151
Yifan Hong326afd12021-05-19 15:24:54 -0700152static void joinRpcServer(sp<RpcServer>&& thiz) {
153 thiz->join();
154}
155
156void RpcServer::start() {
157 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
158 std::lock_guard<std::mutex> _l(mLock);
159 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
160 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
161}
162
Steven Moreland611d15f2021-05-01 01:28:27 +0000163void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700164 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
165
166 {
167 std::lock_guard<std::mutex> _l(mLock);
168 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
169 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
170 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700171 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700172 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000173 }
Yifan Hong1a235852021-05-13 16:07:47 -0700174
Steven Moreland2b4f3802021-05-22 01:46:27 +0000175 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000176 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000177 unique_fd clientFd(TEMP_FAILURE_RETRY(
Yifan Hongb675ffe2021-08-05 16:37:17 -0700178 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC | SOCK_NONBLOCK)));
Steven Moreland410325a2021-06-02 18:37:42 +0000179
180 if (clientFd < 0) {
181 ALOGE("Could not accept4 socket: %s", strerror(errno));
182 continue;
183 }
184 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
185
186 {
187 std::lock_guard<std::mutex> _l(mLock);
188 std::thread thread =
189 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
190 std::move(clientFd));
191 mConnectingThreads[thread.get_id()] = std::move(thread);
192 }
Yifan Hong1a235852021-05-13 16:07:47 -0700193 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000194 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700195
196 {
197 std::lock_guard<std::mutex> _l(mLock);
198 mJoinThreadRunning = false;
199 }
200 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000201}
202
Yifan Hong1a235852021-05-13 16:07:47 -0700203bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700204 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000205 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000206 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000207 return false;
208 }
Yifan Hong1a235852021-05-13 16:07:47 -0700209
210 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700211
Steven Morelanda8b44292021-06-08 01:27:53 +0000212 for (auto& [id, session] : mSessions) {
213 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700214 // server lock is a more general lock
215 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000216 session->mShutdownTrigger->trigger();
217 }
218
Steven Morelandee3f4662021-05-22 01:07:33 +0000219 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000220 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
221 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
222 "Connecting threads: "
223 "%zu, Sessions: %zu. Is your server deadlocked?",
224 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
225 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000226 }
Yifan Hong1a235852021-05-13 16:07:47 -0700227
Yifan Hong326afd12021-05-19 15:24:54 -0700228 // At this point, we know join() is about to exit, but the thread that calls
229 // join() may not have exited yet.
230 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
231 // otherwise ~thread() may call std::terminate(), which may crash the process.
232 // If RpcServer does not own the join thread (aka join() is called directly),
233 // then the owner of RpcServer is responsible for cleaning up that thread.
234 if (mJoinThread.get()) {
235 mJoinThread->join();
236 mJoinThread.reset();
237 }
238
Steven Moreland1c943ec2021-07-13 23:57:56 +0000239 LOG_RPC_DETAIL("Finished waiting on shutdown.");
240
Yifan Hong1a235852021-05-13 16:07:47 -0700241 mShutdownTrigger = nullptr;
242 return true;
243}
244
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000246 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000247 std::vector<sp<RpcSession>> sessions;
248 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000249 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000250 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000251 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000253}
254
Steven Morelandd539fbf2021-05-05 23:40:25 +0000255size_t RpcServer::numUninitializedSessions() {
256 std::lock_guard<std::mutex> _l(mLock);
257 return mConnectingThreads.size();
258}
259
Steven Morelanda63ff932021-05-12 00:03:15 +0000260void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000261 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700262 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000263
264 // mShutdownTrigger can only be cleared once connection threads have joined.
265 // It must be set before this thread is started
266 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700267 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
268
269 status_t status = OK;
270
271 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700272 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700273 if (client == nullptr) {
274 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
275 status = DEAD_OBJECT;
276 // still need to cleanup before we can return
277 } else {
278 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
279 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000280
Steven Moreland659416d2021-05-11 00:47:50 +0000281 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700282 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700283 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
Steven Moreland43921d52021-09-27 17:15:56 -0700284 sizeof(header), {});
Yifan Hong702115c2021-06-24 15:39:18 -0700285 if (status != OK) {
286 ALOGE("Failed to read ID for client connecting to RPC server: %s",
287 statusToString(status).c_str());
288 // still need to cleanup before we can return
289 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000290 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700291
Steven Moreland826367f2021-09-10 14:05:31 -0700292 std::vector<uint8_t> sessionId;
293 if (status == OK) {
294 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700295 if (header.sessionIdSize == kSessionIdBytes) {
296 sessionId.resize(header.sessionIdSize);
297 status = client->interruptableReadFully(server->mShutdownTrigger.get(),
298 sessionId.data(), sessionId.size(), {});
299 if (status != OK) {
300 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
301 statusToString(status).c_str());
302 // still need to cleanup before we can return
303 }
304 } else {
305 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
306 kSessionIdBytes, header.sessionIdSize);
307 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700308 }
309 }
310 }
311
Steven Morelandbf57bce2021-07-26 15:26:12 -0700312 bool incoming = false;
313 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700314 bool requestingNewSession = false;
315
316 if (status == OK) {
317 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
318 protocolVersion = std::min(header.version,
319 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700320 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700321
322 if (requestingNewSession) {
323 RpcNewSessionResponse response{
324 .version = protocolVersion,
325 };
326
Yifan Hong8c950422021-08-05 17:13:55 -0700327 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
Steven Moreland43921d52021-09-27 17:15:56 -0700328 sizeof(response), {});
Steven Morelandbf57bce2021-07-26 15:26:12 -0700329 if (status != OK) {
330 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
331 // still need to cleanup before we can return
332 }
333 }
334 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000335
336 std::thread thisThread;
337 sp<RpcSession> session;
338 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000339 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000340
Yifan Hongb3005502021-05-19 15:37:00 -0700341 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
342 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000343 "Must establish connection on owned thread");
344 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000345 ScopeGuard detachGuard = [&]() {
346 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000347 _l.unlock();
348 server->mShutdownCv.notify_all();
349 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000350 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000351
Steven Morelandbf57bce2021-07-26 15:26:12 -0700352 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000353 return;
354 }
355
Steven Morelandbf57bce2021-07-26 15:26:12 -0700356 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000357 if (incoming) {
358 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000359 return;
360 }
361
Steven Moreland826367f2021-09-10 14:05:31 -0700362 // Uniquely identify session at the application layer. Even if a
363 // client/server use the same certificates, if they create multiple
364 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700365 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000366 size_t tries = 0;
367 do {
368 // don't block if there is some entropy issue
369 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700370 ALOGE("Cannot find new address: %s",
371 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000372 return;
373 }
374
Steven Moreland826367f2021-09-10 14:05:31 -0700375 base::unique_fd fd(TEMP_FAILURE_RETRY(
376 open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
377 if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
378 ALOGE("Could not read from /dev/urandom to create session ID");
379 return;
380 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000381 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000382
383 session = RpcSession::make();
Yifan Hong10423062021-10-08 16:26:32 -0700384 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700385 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000386 if (!session->setForServer(server,
387 sp<RpcServer::EventListener>::fromExisting(
388 static_cast<RpcServer::EventListener*>(
389 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000390 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000391 ALOGE("Failed to attach server to session");
392 return;
393 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000394
Steven Moreland01a6bad2021-06-11 00:59:20 +0000395 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000396 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000397 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700398 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000399 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700400 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000401 return;
402 }
403 session = it->second;
404 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000405
Steven Moreland1b304292021-07-15 22:59:34 +0000406 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700407 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000408 "server state must already be initialized");
409 return;
410 }
411
Steven Moreland5802c2b2021-05-12 20:13:04 +0000412 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000413 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000414 }
415
Yifan Hong702115c2021-06-24 15:39:18 -0700416 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000417
Steven Morelanda63ff932021-05-12 00:03:15 +0000418 // avoid strong cycle
419 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000420
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000421 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000422}
423
Steven Moreland2372f9d2021-08-05 15:42:01 -0700424status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000425 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700426 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000427
Yifan Hongb675ffe2021-08-05 16:37:17 -0700428 unique_fd serverFd(TEMP_FAILURE_RETRY(
429 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000430 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700431 int savedErrno = errno;
432 ALOGE("Could not create socket: %s", strerror(savedErrno));
433 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000434 }
435
436 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
437 int savedErrno = errno;
438 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700439 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000440 }
441
Yifan Honge96a1f12021-07-13 16:08:28 -0700442 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
443 // the backlog is increased to a large number.
444 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
445 // to 1.
446 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000447 int savedErrno = errno;
448 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700449 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000450 }
451
Steven Moreland704fc1a2021-05-04 23:13:14 +0000452 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
453
Steven Moreland2372f9d2021-08-05 15:42:01 -0700454 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700455 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700456 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700457 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700458 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000459}
460
Steven Morelanddd67b942021-07-23 17:15:41 -0700461void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700462 const std::vector<uint8_t>& id = session->mId;
463 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
464 LOG_RPC_DETAIL("Dropping session with address %s",
465 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000466
467 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700468 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000469 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700470 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000471 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700472 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000473 (void)mSessions.erase(it);
474}
475
Steven Moreland19fc9f72021-06-10 03:57:30 +0000476void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000477 mShutdownCv.notify_all();
478}
479
Yifan Hong0eb5a672021-05-12 18:00:25 -0700480bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700481 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700482 std::lock_guard<std::mutex> _l(mLock);
483 return mServer.ok();
484}
485
Yifan Hong00aeb762021-05-12 17:07:36 -0700486unique_fd RpcServer::releaseServer() {
487 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
488 std::lock_guard<std::mutex> _l(mLock);
489 return std::move(mServer);
490}
491
Steven Moreland2372f9d2021-08-05 15:42:01 -0700492status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700493 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
494 std::lock_guard<std::mutex> _l(mLock);
495 if (mServer.ok()) {
496 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700497 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700498 }
499 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700501}
502
Steven Moreland5553ac42020-11-11 02:14:45 +0000503} // namespace android