blob: 5733993b3bf067e999ad1178c305b6abf1817aa3 [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 Moreland826367f2021-09-10 14:05:31 -070026#include <android-base/file.h>
27#include <android-base/hex.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000028#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029#include <binder/Parcel.h>
30#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070031#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <log/log.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033
Yifan Hong8c950422021-08-05 17:13:55 -070034#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000035#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070036#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000037#include "RpcWireFormat.h"
38
39namespace android {
40
Steven Moreland5802c2b2021-05-12 20:13:04 +000041using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000042using base::unique_fd;
43
Yifan Hongecf937d2021-08-11 17:29:28 -070044RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070045RpcServer::~RpcServer() {
46 (void)shutdown();
47}
Steven Moreland5553ac42020-11-11 02:14:45 +000048
Yifan Hong702115c2021-06-24 15:39:18 -070049sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
50 // Default is without TLS.
51 if (rpcTransportCtxFactory == nullptr)
52 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070053 auto ctx = rpcTransportCtxFactory->newServerCtx();
54 if (ctx == nullptr) return nullptr;
55 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000056}
57
58void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
59 mAgreedExperimental = true;
60}
61
Steven Moreland2372f9d2021-08-05 15:42:01 -070062status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000063 return setupSocketServer(UnixSocketAddress(path));
64}
65
Steven Moreland2372f9d2021-08-05 15:42:01 -070066status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000067 // realizing value w/ this type at compile time to avoid ubsan abort
68 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
69
70 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
71}
72
Steven Moreland2372f9d2021-08-05 15:42:01 -070073status_t RpcServer::setupInetServer(const char* address, unsigned int port,
74 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000075 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000076 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070077 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000078 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000079 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070080 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000081 continue;
82 }
83
84 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
85 sockaddr_in addr{};
86 socklen_t len = sizeof(addr);
87 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
88 int savedErrno = errno;
89 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
90 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070091 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000092 }
93 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
94 static_cast<size_t>(len), sizeof(addr));
95 unsigned int realPort = ntohs(addr.sin_port);
96 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
97 "Requesting inet server on %s but it is set up on %u.",
98 socketAddress.toString().c_str(), realPort);
99
100 if (assignedPort != nullptr) {
101 *assignedPort = realPort;
102 }
103
Steven Moreland2372f9d2021-08-05 15:42:01 -0700104 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000105 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000106 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 +0000107 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700108 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000109}
110
Steven Morelandf137de92021-04-24 01:54:26 +0000111void RpcServer::setMaxThreads(size_t threads) {
112 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700113 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000114 mMaxThreads = threads;
115}
116
117size_t RpcServer::getMaxThreads() {
118 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119}
120
Steven Morelandbf57bce2021-07-26 15:26:12 -0700121void RpcServer::setProtocolVersion(uint32_t version) {
122 mProtocolVersion = version;
123}
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000126 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700127 mRootObjectWeak = mRootObject = binder;
128}
129
130void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
131 std::lock_guard<std::mutex> _l(mLock);
132 mRootObject.clear();
133 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000134}
135
136sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000137 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700138 bool hasWeak = mRootObjectWeak.unsafe_get();
139 sp<IBinder> ret = mRootObjectWeak.promote();
140 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
141 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000142}
143
Yifan Hong9734cfc2021-09-13 16:14:09 -0700144std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700145 std::lock_guard<std::mutex> _l(mLock);
146 return mCtx->getCertificate(format);
147}
148
Yifan Hong326afd12021-05-19 15:24:54 -0700149static void joinRpcServer(sp<RpcServer>&& thiz) {
150 thiz->join();
151}
152
153void RpcServer::start() {
154 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
155 std::lock_guard<std::mutex> _l(mLock);
156 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
157 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
158}
159
Steven Moreland611d15f2021-05-01 01:28:27 +0000160void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700161 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
162
163 {
164 std::lock_guard<std::mutex> _l(mLock);
165 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
166 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
167 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700168 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700169 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000170 }
Yifan Hong1a235852021-05-13 16:07:47 -0700171
Steven Moreland2b4f3802021-05-22 01:46:27 +0000172 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000173 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000174 unique_fd clientFd(TEMP_FAILURE_RETRY(
Yifan Hongb675ffe2021-08-05 16:37:17 -0700175 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC | SOCK_NONBLOCK)));
Steven Moreland410325a2021-06-02 18:37:42 +0000176
177 if (clientFd < 0) {
178 ALOGE("Could not accept4 socket: %s", strerror(errno));
179 continue;
180 }
181 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
182
183 {
184 std::lock_guard<std::mutex> _l(mLock);
185 std::thread thread =
186 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
187 std::move(clientFd));
188 mConnectingThreads[thread.get_id()] = std::move(thread);
189 }
Yifan Hong1a235852021-05-13 16:07:47 -0700190 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000191 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700192
193 {
194 std::lock_guard<std::mutex> _l(mLock);
195 mJoinThreadRunning = false;
196 }
197 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000198}
199
Yifan Hong1a235852021-05-13 16:07:47 -0700200bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700201 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000202 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000203 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000204 return false;
205 }
Yifan Hong1a235852021-05-13 16:07:47 -0700206
207 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000208 for (auto& [id, session] : mSessions) {
209 (void)id;
210 session->mShutdownTrigger->trigger();
211 }
212
Steven Morelandee3f4662021-05-22 01:07:33 +0000213 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000214 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
215 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
216 "Connecting threads: "
217 "%zu, Sessions: %zu. Is your server deadlocked?",
218 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
219 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000220 }
Yifan Hong1a235852021-05-13 16:07:47 -0700221
Yifan Hong326afd12021-05-19 15:24:54 -0700222 // At this point, we know join() is about to exit, but the thread that calls
223 // join() may not have exited yet.
224 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
225 // otherwise ~thread() may call std::terminate(), which may crash the process.
226 // If RpcServer does not own the join thread (aka join() is called directly),
227 // then the owner of RpcServer is responsible for cleaning up that thread.
228 if (mJoinThread.get()) {
229 mJoinThread->join();
230 mJoinThread.reset();
231 }
232
Steven Moreland1c943ec2021-07-13 23:57:56 +0000233 LOG_RPC_DETAIL("Finished waiting on shutdown.");
234
Yifan Hong1a235852021-05-13 16:07:47 -0700235 mShutdownTrigger = nullptr;
236 return true;
237}
238
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000240 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241 std::vector<sp<RpcSession>> sessions;
242 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000243 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000245 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000246 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000247}
248
Steven Morelandd539fbf2021-05-05 23:40:25 +0000249size_t RpcServer::numUninitializedSessions() {
250 std::lock_guard<std::mutex> _l(mLock);
251 return mConnectingThreads.size();
252}
253
Steven Morelanda63ff932021-05-12 00:03:15 +0000254void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000255 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700256 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000257
258 // mShutdownTrigger can only be cleared once connection threads have joined.
259 // It must be set before this thread is started
260 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700261 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
262
263 status_t status = OK;
264
265 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700266 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700267 if (client == nullptr) {
268 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
269 status = DEAD_OBJECT;
270 // still need to cleanup before we can return
271 } else {
272 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
273 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000274
Steven Moreland659416d2021-05-11 00:47:50 +0000275 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700276 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700277 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
278 sizeof(header));
Yifan Hong702115c2021-06-24 15:39:18 -0700279 if (status != OK) {
280 ALOGE("Failed to read ID for client connecting to RPC server: %s",
281 statusToString(status).c_str());
282 // still need to cleanup before we can return
283 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000284 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700285
Steven Moreland826367f2021-09-10 14:05:31 -0700286 std::vector<uint8_t> sessionId;
287 if (status == OK) {
288 if (header.sessionIdSize > 0) {
289 sessionId.resize(header.sessionIdSize);
290 status = client->interruptableReadFully(server->mShutdownTrigger.get(),
291 sessionId.data(), sessionId.size());
292 if (status != OK) {
293 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
294 statusToString(status).c_str());
295 // still need to cleanup before we can return
296 }
297 }
298 }
299
Steven Morelandbf57bce2021-07-26 15:26:12 -0700300 bool incoming = false;
301 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700302 bool requestingNewSession = false;
303
304 if (status == OK) {
305 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
306 protocolVersion = std::min(header.version,
307 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700308 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700309
310 if (requestingNewSession) {
311 RpcNewSessionResponse response{
312 .version = protocolVersion,
313 };
314
Yifan Hong8c950422021-08-05 17:13:55 -0700315 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
316 sizeof(response));
Steven Morelandbf57bce2021-07-26 15:26:12 -0700317 if (status != OK) {
318 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
319 // still need to cleanup before we can return
320 }
321 }
322 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000323
324 std::thread thisThread;
325 sp<RpcSession> session;
326 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000327 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000328
Yifan Hongb3005502021-05-19 15:37:00 -0700329 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
330 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000331 "Must establish connection on owned thread");
332 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000333 ScopeGuard detachGuard = [&]() {
334 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000335 _l.unlock();
336 server->mShutdownCv.notify_all();
337 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000338 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000339
Steven Morelandbf57bce2021-07-26 15:26:12 -0700340 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000341 return;
342 }
343
Steven Morelandbf57bce2021-07-26 15:26:12 -0700344 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000345 if (incoming) {
346 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000347 return;
348 }
349
Steven Moreland826367f2021-09-10 14:05:31 -0700350 // Uniquely identify session at the application layer. Even if a
351 // client/server use the same certificates, if they create multiple
352 // sessions, we still want to distinguish between them.
353 constexpr size_t kSessionIdSize = 32;
354 sessionId.resize(kSessionIdSize);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000355 size_t tries = 0;
356 do {
357 // don't block if there is some entropy issue
358 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700359 ALOGE("Cannot find new address: %s",
360 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000361 return;
362 }
363
Steven Moreland826367f2021-09-10 14:05:31 -0700364 base::unique_fd fd(TEMP_FAILURE_RETRY(
365 open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
366 if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
367 ALOGE("Could not read from /dev/urandom to create session ID");
368 return;
369 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000370 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000371
372 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000373 session->setMaxThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700374 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Morelanda8b44292021-06-08 01:27:53 +0000375 if (!session->setForServer(server,
376 sp<RpcServer::EventListener>::fromExisting(
377 static_cast<RpcServer::EventListener*>(
378 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000379 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000380 ALOGE("Failed to attach server to session");
381 return;
382 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000383
Steven Moreland01a6bad2021-06-11 00:59:20 +0000384 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000385 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000386 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700387 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000388 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700389 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000390 return;
391 }
392 session = it->second;
393 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000394
Steven Moreland1b304292021-07-15 22:59:34 +0000395 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700396 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000397 "server state must already be initialized");
398 return;
399 }
400
Steven Moreland5802c2b2021-05-12 20:13:04 +0000401 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000402 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000403 }
404
Yifan Hong702115c2021-06-24 15:39:18 -0700405 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000406
Steven Morelanda63ff932021-05-12 00:03:15 +0000407 // avoid strong cycle
408 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000409
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000410 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000411}
412
Steven Moreland2372f9d2021-08-05 15:42:01 -0700413status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000414 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700415 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000416
Yifan Hongb675ffe2021-08-05 16:37:17 -0700417 unique_fd serverFd(TEMP_FAILURE_RETRY(
418 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000419 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700420 int savedErrno = errno;
421 ALOGE("Could not create socket: %s", strerror(savedErrno));
422 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000423 }
424
425 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
426 int savedErrno = errno;
427 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700428 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000429 }
430
Yifan Honge96a1f12021-07-13 16:08:28 -0700431 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
432 // the backlog is increased to a large number.
433 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
434 // to 1.
435 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000436 int savedErrno = errno;
437 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700438 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000439 }
440
Steven Moreland704fc1a2021-05-04 23:13:14 +0000441 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
442
Steven Moreland2372f9d2021-08-05 15:42:01 -0700443 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700444 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700445 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700446 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700447 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000448}
449
Steven Morelanddd67b942021-07-23 17:15:41 -0700450void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700451 const std::vector<uint8_t>& id = session->mId;
452 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
453 LOG_RPC_DETAIL("Dropping session with address %s",
454 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000455
456 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700457 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000458 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700459 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000460 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700461 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000462 (void)mSessions.erase(it);
463}
464
Steven Moreland19fc9f72021-06-10 03:57:30 +0000465void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000466 mShutdownCv.notify_all();
467}
468
Yifan Hong0eb5a672021-05-12 18:00:25 -0700469bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700470 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700471 std::lock_guard<std::mutex> _l(mLock);
472 return mServer.ok();
473}
474
Yifan Hong00aeb762021-05-12 17:07:36 -0700475unique_fd RpcServer::releaseServer() {
476 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
477 std::lock_guard<std::mutex> _l(mLock);
478 return std::move(mServer);
479}
480
Steven Moreland2372f9d2021-08-05 15:42:01 -0700481status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700482 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
483 std::lock_guard<std::mutex> _l(mLock);
484 if (mServer.ok()) {
485 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700486 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700487 }
488 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700489 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700490}
491
Steven Moreland5553ac42020-11-11 02:14:45 +0000492} // namespace android