blob: 424a210501d5262c48889c39810c79a67a0cacd4 [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
Yifan Hong1a235852021-05-13 16:07:47 -070019#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
Yifan Hong1a235852021-05-13 16:07:47 -070026#include <android-base/macros.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000027#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/Parcel.h>
29#include <binder/RpcServer.h>
30#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
Steven Moreland5553ac42020-11-11 02:14:45 +000041RpcServer::RpcServer() {}
42RpcServer::~RpcServer() {}
43
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 Hong1a235852021-05-13 16:07:47 -0700131std::unique_ptr<RpcServer::FdTrigger> RpcServer::FdTrigger::make() {
132 auto ret = std::make_unique<RpcServer::FdTrigger>();
133 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) return nullptr;
134 return ret;
135}
136
137void RpcServer::FdTrigger::trigger() {
138 mWrite.reset();
139}
140
Steven Moreland611d15f2021-05-01 01:28:27 +0000141void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700142 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
143
144 {
145 std::lock_guard<std::mutex> _l(mLock);
146 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
147 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
148 mJoinThreadRunning = true;
149 mShutdownTrigger = FdTrigger::make();
150 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000151 }
Yifan Hong1a235852021-05-13 16:07:47 -0700152
153 while (true) {
154 pollfd pfd[]{{.fd = mServer.get(), .events = POLLIN, .revents = 0},
155 {.fd = mShutdownTrigger->readFd().get(), .events = POLLHUP, .revents = 0}};
156 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
157 if (ret < 0) {
158 ALOGE("Could not poll socket: %s", strerror(errno));
159 continue;
160 }
161 if (ret == 0) {
162 continue;
163 }
164 if (pfd[1].revents & POLLHUP) {
165 LOG_RPC_DETAIL("join() exiting because shutdown requested.");
166 break;
167 }
168
169 (void)acceptOneNoCheck();
170 }
171
172 {
173 std::lock_guard<std::mutex> _l(mLock);
174 mJoinThreadRunning = false;
175 }
176 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000177}
178
179bool RpcServer::acceptOne() {
Steven Morelandf137de92021-04-24 01:54:26 +0000180 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong1a235852021-05-13 16:07:47 -0700181 LOG_ALWAYS_FATAL_IF(!hasServer(), "RpcServer must be setup to acceptOne.");
182 return acceptOneNoCheck();
183}
Steven Morelandd539fbf2021-05-05 23:40:25 +0000184
Yifan Hong1a235852021-05-13 16:07:47 -0700185bool RpcServer::acceptOneNoCheck() {
Steven Morelandd539fbf2021-05-05 23:40:25 +0000186 unique_fd clientFd(
187 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
188
189 if (clientFd < 0) {
190 ALOGE("Could not accept4 socket: %s", strerror(errno));
191 return false;
192 }
193 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
194
Steven Morelandf137de92021-04-24 01:54:26 +0000195 {
196 std::lock_guard<std::mutex> _l(mLock);
Yifan Hongb3005502021-05-19 15:37:00 -0700197 std::thread thread = std::thread(&RpcServer::establishConnection,
198 sp<RpcServer>::fromExisting(this), std::move(clientFd));
Steven Morelandd539fbf2021-05-05 23:40:25 +0000199 mConnectingThreads[thread.get_id()] = std::move(thread);
Steven Morelandf137de92021-04-24 01:54:26 +0000200 }
201
Steven Morelandd539fbf2021-05-05 23:40:25 +0000202 return true;
Steven Morelandf137de92021-04-24 01:54:26 +0000203}
204
Yifan Hong1a235852021-05-13 16:07:47 -0700205bool RpcServer::shutdown() {
206 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
207 std::unique_lock<std::mutex> _l(mLock);
208 if (mShutdownTrigger == nullptr) return false;
209
210 mShutdownTrigger->trigger();
211 while (mJoinThreadRunning) mShutdownCv.wait(_l);
212
213 mShutdownTrigger = nullptr;
214 return true;
215}
216
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000218 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000219 std::vector<sp<RpcSession>> sessions;
220 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000221 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000222 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000223 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000224 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000225}
226
Steven Morelandd539fbf2021-05-05 23:40:25 +0000227size_t RpcServer::numUninitializedSessions() {
228 std::lock_guard<std::mutex> _l(mLock);
229 return mConnectingThreads.size();
230}
231
Steven Morelanda63ff932021-05-12 00:03:15 +0000232void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000233 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700234 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland5802c2b2021-05-12 20:13:04 +0000235 bool idValid = true;
Steven Morelanda63ff932021-05-12 00:03:15 +0000236 int32_t id;
237 if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
238 ALOGE("Could not read ID from fd %d", clientFd.get());
Steven Moreland5802c2b2021-05-12 20:13:04 +0000239 idValid = false;
Steven Morelanda63ff932021-05-12 00:03:15 +0000240 }
241
242 std::thread thisThread;
243 sp<RpcSession> session;
244 {
Yifan Hongb3005502021-05-19 15:37:00 -0700245 std::lock_guard<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000246
Yifan Hongb3005502021-05-19 15:37:00 -0700247 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
248 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000249 "Must establish connection on owned thread");
250 thisThread = std::move(threadId->second);
Steven Moreland5802c2b2021-05-12 20:13:04 +0000251 ScopeGuard detachGuard = [&]() { thisThread.detach(); };
Yifan Hongb3005502021-05-19 15:37:00 -0700252 server->mConnectingThreads.erase(threadId);
Steven Morelanda63ff932021-05-12 00:03:15 +0000253
Steven Moreland5802c2b2021-05-12 20:13:04 +0000254 if (!idValid) {
255 return;
256 }
257
Steven Morelanda63ff932021-05-12 00:03:15 +0000258 if (id == RPC_SESSION_ID_NEW) {
Yifan Hongb3005502021-05-19 15:37:00 -0700259 LOG_ALWAYS_FATAL_IF(server->mSessionIdCounter >= INT32_MAX, "Out of session IDs");
260 server->mSessionIdCounter++;
Steven Morelanda63ff932021-05-12 00:03:15 +0000261
262 session = RpcSession::make();
Yifan Hongb3005502021-05-19 15:37:00 -0700263 session->setForServer(wp<RpcServer>(server), server->mSessionIdCounter);
Steven Morelanda63ff932021-05-12 00:03:15 +0000264
Yifan Hongb3005502021-05-19 15:37:00 -0700265 server->mSessions[server->mSessionIdCounter] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000266 } else {
Yifan Hongb3005502021-05-19 15:37:00 -0700267 auto it = server->mSessions.find(id);
268 if (it == server->mSessions.end()) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000269 ALOGE("Cannot add thread, no record of session with ID %d", id);
270 return;
271 }
272 session = it->second;
273 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000274
275 detachGuard.Disable();
276 session->preJoin(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000277 }
278
279 // avoid strong cycle
280 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000281
Steven Moreland5802c2b2021-05-12 20:13:04 +0000282 session->join(std::move(clientFd));
Steven Morelanda63ff932021-05-12 00:03:15 +0000283}
284
Steven Moreland611d15f2021-05-01 01:28:27 +0000285bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000286 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700287 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000288
289 unique_fd serverFd(
290 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
291 if (serverFd == -1) {
292 ALOGE("Could not create socket: %s", strerror(errno));
293 return false;
294 }
295
296 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
297 int savedErrno = errno;
298 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
299 return false;
300 }
301
302 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
303 int savedErrno = errno;
304 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
305 return false;
306 }
307
Steven Moreland704fc1a2021-05-04 23:13:14 +0000308 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
309
Yifan Hongc276f8d2021-05-13 17:13:44 -0700310 if (!setupExternalServer(std::move(serverFd))) {
311 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
312 return false;
313 }
Steven Moreland611d15f2021-05-01 01:28:27 +0000314 return true;
315}
316
Steven Morelandee78e762021-05-05 21:12:51 +0000317void RpcServer::onSessionTerminating(const sp<RpcSession>& session) {
318 auto id = session->mId;
319 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
320 LOG_RPC_DETAIL("Dropping session %d", *id);
321
322 std::lock_guard<std::mutex> _l(mLock);
323 auto it = mSessions.find(*id);
324 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %d", *id);
325 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %d", *id);
326 (void)mSessions.erase(it);
327}
328
Yifan Hong0eb5a672021-05-12 18:00:25 -0700329bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700330 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700331 std::lock_guard<std::mutex> _l(mLock);
332 return mServer.ok();
333}
334
Yifan Hong00aeb762021-05-12 17:07:36 -0700335unique_fd RpcServer::releaseServer() {
336 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
337 std::lock_guard<std::mutex> _l(mLock);
338 return std::move(mServer);
339}
340
341bool RpcServer::setupExternalServer(base::unique_fd serverFd) {
342 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
343 std::lock_guard<std::mutex> _l(mLock);
344 if (mServer.ok()) {
345 ALOGE("Each RpcServer can only have one server.");
346 return false;
347 }
348 mServer = std::move(serverFd);
349 return true;
350}
351
Steven Moreland5553ac42020-11-11 02:14:45 +0000352} // namespace android