blob: 9943e470212025c4ec423a03deca6789a9d5b97f [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
19#include <sys/socket.h>
20#include <sys/un.h>
21
Steven Morelandf137de92021-04-24 01:54:26 +000022#include <thread>
Steven Moreland5553ac42020-11-11 02:14:45 +000023#include <vector>
24
Steven Moreland5802c2b2021-05-12 20:13:04 +000025#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000026#include <binder/Parcel.h>
27#include <binder/RpcServer.h>
28#include <log/log.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029
Steven Moreland611d15f2021-05-01 01:28:27 +000030#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070031#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include "RpcWireFormat.h"
33
34namespace android {
35
Steven Moreland5802c2b2021-05-12 20:13:04 +000036using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000037using base::unique_fd;
38
Steven Moreland5553ac42020-11-11 02:14:45 +000039RpcServer::RpcServer() {}
Yifan Hong436f0e62021-05-19 15:25:34 -070040RpcServer::~RpcServer() {
41 (void)shutdown();
42}
Steven Moreland5553ac42020-11-11 02:14:45 +000043
44sp<RpcServer> RpcServer::make() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +000045 return sp<RpcServer>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +000046}
47
48void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
49 mAgreedExperimental = true;
50}
51
Steven Moreland611d15f2021-05-01 01:28:27 +000052bool RpcServer::setupUnixDomainServer(const char* path) {
53 return setupSocketServer(UnixSocketAddress(path));
54}
55
Steven Moreland611d15f2021-05-01 01:28:27 +000056bool RpcServer::setupVsockServer(unsigned int port) {
57 // realizing value w/ this type at compile time to avoid ubsan abort
58 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
59
60 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
61}
62
Steven Moreland611d15f2021-05-01 01:28:27 +000063bool RpcServer::setupInetServer(unsigned int port, unsigned int* assignedPort) {
64 const char* kAddr = "127.0.0.1";
65
66 if (assignedPort != nullptr) *assignedPort = 0;
67 auto aiStart = InetSocketAddress::getAddrInfo(kAddr, port);
68 if (aiStart == nullptr) return false;
69 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
70 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, kAddr, port);
71 if (!setupSocketServer(socketAddress)) {
72 continue;
73 }
74
75 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
76 sockaddr_in addr{};
77 socklen_t len = sizeof(addr);
78 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
79 int savedErrno = errno;
80 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
81 strerror(savedErrno));
82 return false;
83 }
84 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
85 static_cast<size_t>(len), sizeof(addr));
86 unsigned int realPort = ntohs(addr.sin_port);
87 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
88 "Requesting inet server on %s but it is set up on %u.",
89 socketAddress.toString().c_str(), realPort);
90
91 if (assignedPort != nullptr) {
92 *assignedPort = realPort;
93 }
94
95 return true;
96 }
97 ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", kAddr,
98 port);
99 return false;
100}
101
Steven Morelandf137de92021-04-24 01:54:26 +0000102void RpcServer::setMaxThreads(size_t threads) {
103 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700104 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000105 mMaxThreads = threads;
106}
107
108size_t RpcServer::getMaxThreads() {
109 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000110}
111
112void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000113 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700114 mRootObjectWeak = mRootObject = binder;
115}
116
117void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
118 std::lock_guard<std::mutex> _l(mLock);
119 mRootObject.clear();
120 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000121}
122
123sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000124 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700125 bool hasWeak = mRootObjectWeak.unsafe_get();
126 sp<IBinder> ret = mRootObjectWeak.promote();
127 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
128 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000129}
130
Yifan Hong326afd12021-05-19 15:24:54 -0700131static void joinRpcServer(sp<RpcServer>&& thiz) {
132 thiz->join();
133}
134
135void RpcServer::start() {
136 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
137 std::lock_guard<std::mutex> _l(mLock);
138 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
139 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
140}
141
Steven Moreland611d15f2021-05-01 01:28:27 +0000142void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700143 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
144
145 {
146 std::lock_guard<std::mutex> _l(mLock);
147 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
148 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
149 mJoinThreadRunning = true;
Steven Morelande47511f2021-05-20 00:07:41 +0000150 mShutdownTrigger = RpcSession::FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700151 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000152 }
Yifan Hong1a235852021-05-13 16:07:47 -0700153
Steven Moreland2b4f3802021-05-22 01:46:27 +0000154 status_t status;
155 while ((status = mShutdownTrigger->triggerablePollRead(mServer)) == OK) {
Steven Moreland410325a2021-06-02 18:37:42 +0000156 unique_fd clientFd(TEMP_FAILURE_RETRY(
157 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
158
159 if (clientFd < 0) {
160 ALOGE("Could not accept4 socket: %s", strerror(errno));
161 continue;
162 }
163 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
164
165 {
166 std::lock_guard<std::mutex> _l(mLock);
167 std::thread thread =
168 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
169 std::move(clientFd));
170 mConnectingThreads[thread.get_id()] = std::move(thread);
171 }
Yifan Hong1a235852021-05-13 16:07:47 -0700172 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000173 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700174
175 {
176 std::lock_guard<std::mutex> _l(mLock);
177 mJoinThreadRunning = false;
178 }
179 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000180}
181
Yifan Hong1a235852021-05-13 16:07:47 -0700182bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700183 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000184 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000185 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000186 return false;
187 }
Yifan Hong1a235852021-05-13 16:07:47 -0700188
189 mShutdownTrigger->trigger();
Steven Morelanda8b44292021-06-08 01:27:53 +0000190 for (auto& [id, session] : mSessions) {
191 (void)id;
192 session->mShutdownTrigger->trigger();
193 }
194
Steven Morelandee3f4662021-05-22 01:07:33 +0000195 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000196 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
197 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
198 "Connecting threads: "
199 "%zu, Sessions: %zu. Is your server deadlocked?",
200 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
201 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000202 }
Yifan Hong1a235852021-05-13 16:07:47 -0700203
Yifan Hong326afd12021-05-19 15:24:54 -0700204 // At this point, we know join() is about to exit, but the thread that calls
205 // join() may not have exited yet.
206 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
207 // otherwise ~thread() may call std::terminate(), which may crash the process.
208 // If RpcServer does not own the join thread (aka join() is called directly),
209 // then the owner of RpcServer is responsible for cleaning up that thread.
210 if (mJoinThread.get()) {
211 mJoinThread->join();
212 mJoinThread.reset();
213 }
214
Steven Moreland1c943ec2021-07-13 23:57:56 +0000215 LOG_RPC_DETAIL("Finished waiting on shutdown.");
216
Yifan Hong1a235852021-05-13 16:07:47 -0700217 mShutdownTrigger = nullptr;
218 return true;
219}
220
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000221std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000222 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 std::vector<sp<RpcSession>> sessions;
224 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000225 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000226 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000227 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000228 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000229}
230
Steven Morelandd539fbf2021-05-05 23:40:25 +0000231size_t RpcServer::numUninitializedSessions() {
232 std::lock_guard<std::mutex> _l(mLock);
233 return mConnectingThreads.size();
234}
235
Steven Morelanda63ff932021-05-12 00:03:15 +0000236void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000237 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700238 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000239
240 // mShutdownTrigger can only be cleared once connection threads have joined.
241 // It must be set before this thread is started
242 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
243
Steven Moreland659416d2021-05-11 00:47:50 +0000244 RpcConnectionHeader header;
245 status_t status = server->mShutdownTrigger->interruptableReadFully(clientFd.get(), &header,
246 sizeof(header));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000247 bool idValid = status == OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000248 if (!idValid) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000249 ALOGE("Failed to read ID for client connecting to RPC server: %s",
250 statusToString(status).c_str());
251 // still need to cleanup before we can return
Steven Morelanda63ff932021-05-12 00:03:15 +0000252 }
Steven Moreland659416d2021-05-11 00:47:50 +0000253 bool reverse = header.options & RPC_CONNECTION_OPTION_REVERSE;
Steven Morelanda63ff932021-05-12 00:03:15 +0000254
255 std::thread thisThread;
256 sp<RpcSession> session;
257 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000258 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000259
Yifan Hongb3005502021-05-19 15:37:00 -0700260 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
261 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000262 "Must establish connection on owned thread");
263 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000264 ScopeGuard detachGuard = [&]() {
265 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000266 _l.unlock();
267 server->mShutdownCv.notify_all();
268 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000269 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000270
Steven Morelanda8b44292021-06-08 01:27:53 +0000271 if (!idValid || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000272 return;
273 }
274
Steven Moreland01a6bad2021-06-11 00:59:20 +0000275 RpcAddress sessionId = RpcAddress::fromRawEmbedded(&header.sessionId);
276
277 if (sessionId.isZero()) {
Steven Moreland659416d2021-05-11 00:47:50 +0000278 if (reverse) {
279 ALOGE("Cannot create a new session with a reverse connection, would leak");
280 return;
281 }
282
Yifan Hong6fe19632021-06-24 15:50:12 -0700283 sessionId = RpcAddress::zero();
Steven Moreland01a6bad2021-06-11 00:59:20 +0000284 size_t tries = 0;
285 do {
286 // don't block if there is some entropy issue
287 if (tries++ > 5) {
288 ALOGE("Cannot find new address: %s", sessionId.toString().c_str());
289 return;
290 }
291
292 sessionId = RpcAddress::random(true /*forServer*/);
293 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000294
295 session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000296 session->setMaxThreads(server->mMaxThreads);
Steven Morelanda8b44292021-06-08 01:27:53 +0000297 if (!session->setForServer(server,
298 sp<RpcServer::EventListener>::fromExisting(
299 static_cast<RpcServer::EventListener*>(
300 server.get())),
Steven Moreland01a6bad2021-06-11 00:59:20 +0000301 sessionId)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000302 ALOGE("Failed to attach server to session");
303 return;
304 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000305
Steven Moreland01a6bad2021-06-11 00:59:20 +0000306 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000307 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000308 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700309 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000310 ALOGE("Cannot add thread, no record of session with ID %s",
311 sessionId.toString().c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000312 return;
313 }
314 session = it->second;
315 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000316
Steven Moreland659416d2021-05-11 00:47:50 +0000317 if (reverse) {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000318 LOG_ALWAYS_FATAL_IF(!session->addOutgoingConnection(std::move(clientFd), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000319 "server state must already be initialized");
320 return;
321 }
322
Steven Moreland5802c2b2021-05-12 20:13:04 +0000323 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000324 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000325 }
326
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000327 auto setupResult = session->preJoinSetup(std::move(clientFd));
328
Steven Morelanda63ff932021-05-12 00:03:15 +0000329 // avoid strong cycle
330 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000331
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000332 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000333}
334
Steven Moreland611d15f2021-05-01 01:28:27 +0000335bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000336 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700337 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000338
339 unique_fd serverFd(
340 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
341 if (serverFd == -1) {
342 ALOGE("Could not create socket: %s", strerror(errno));
343 return false;
344 }
345
346 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
347 int savedErrno = errno;
348 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
349 return false;
350 }
351
352 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
353 int savedErrno = errno;
354 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
355 return false;
356 }
357
Steven Moreland704fc1a2021-05-04 23:13:14 +0000358 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
359
Yifan Hongc276f8d2021-05-13 17:13:44 -0700360 if (!setupExternalServer(std::move(serverFd))) {
361 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
362 return false;
363 }
Steven Moreland611d15f2021-05-01 01:28:27 +0000364 return true;
365}
366
Steven Moreland19fc9f72021-06-10 03:57:30 +0000367void RpcServer::onSessionLockedAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Morelandee78e762021-05-05 21:12:51 +0000368 auto id = session->mId;
369 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
Steven Moreland01a6bad2021-06-11 00:59:20 +0000370 LOG_RPC_DETAIL("Dropping session with address %s", id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000371
372 std::lock_guard<std::mutex> _l(mLock);
373 auto it = mSessions.find(*id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000374 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
375 id->toString().c_str());
376 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
377 id->toString().c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000378 (void)mSessions.erase(it);
379}
380
Steven Moreland19fc9f72021-06-10 03:57:30 +0000381void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000382 mShutdownCv.notify_all();
383}
384
Yifan Hong0eb5a672021-05-12 18:00:25 -0700385bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700386 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700387 std::lock_guard<std::mutex> _l(mLock);
388 return mServer.ok();
389}
390
Yifan Hong00aeb762021-05-12 17:07:36 -0700391unique_fd RpcServer::releaseServer() {
392 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
393 std::lock_guard<std::mutex> _l(mLock);
394 return std::move(mServer);
395}
396
397bool RpcServer::setupExternalServer(base::unique_fd serverFd) {
398 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
399 std::lock_guard<std::mutex> _l(mLock);
400 if (mServer.ok()) {
401 ALOGE("Each RpcServer can only have one server.");
402 return false;
403 }
404 mServer = std::move(serverFd);
405 return true;
406}
407
Steven Moreland5553ac42020-11-11 02:14:45 +0000408} // namespace android