blob: 59659bd0a6f5ef869a97d73ce581a2e4d052198f [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>
29#include "RpcState.h"
30
Steven Moreland611d15f2021-05-01 01:28:27 +000031#include "RpcSocketAddress.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() {}
40RpcServer::~RpcServer() {}
41
42sp<RpcServer> RpcServer::make() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +000043 return sp<RpcServer>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +000044}
45
46void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
47 mAgreedExperimental = true;
48}
49
Steven Moreland611d15f2021-05-01 01:28:27 +000050bool RpcServer::setupUnixDomainServer(const char* path) {
51 return setupSocketServer(UnixSocketAddress(path));
52}
53
Steven Moreland611d15f2021-05-01 01:28:27 +000054bool RpcServer::setupVsockServer(unsigned int port) {
55 // realizing value w/ this type at compile time to avoid ubsan abort
56 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
57
58 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
59}
60
Steven Moreland611d15f2021-05-01 01:28:27 +000061bool RpcServer::setupInetServer(unsigned int port, unsigned int* assignedPort) {
62 const char* kAddr = "127.0.0.1";
63
64 if (assignedPort != nullptr) *assignedPort = 0;
65 auto aiStart = InetSocketAddress::getAddrInfo(kAddr, port);
66 if (aiStart == nullptr) return false;
67 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
68 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, kAddr, port);
69 if (!setupSocketServer(socketAddress)) {
70 continue;
71 }
72
73 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
74 sockaddr_in addr{};
75 socklen_t len = sizeof(addr);
76 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
77 int savedErrno = errno;
78 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
79 strerror(savedErrno));
80 return false;
81 }
82 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
83 static_cast<size_t>(len), sizeof(addr));
84 unsigned int realPort = ntohs(addr.sin_port);
85 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
86 "Requesting inet server on %s but it is set up on %u.",
87 socketAddress.toString().c_str(), realPort);
88
89 if (assignedPort != nullptr) {
90 *assignedPort = realPort;
91 }
92
93 return true;
94 }
95 ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", kAddr,
96 port);
97 return false;
98}
99
Steven Morelandf137de92021-04-24 01:54:26 +0000100void RpcServer::setMaxThreads(size_t threads) {
101 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Steven Moreland611d15f2021-05-01 01:28:27 +0000102 LOG_ALWAYS_FATAL_IF(mStarted, "must be called before started");
Steven Morelandf137de92021-04-24 01:54:26 +0000103 mMaxThreads = threads;
104}
105
106size_t RpcServer::getMaxThreads() {
107 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000108}
109
110void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000111 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700112 mRootObjectWeak = mRootObject = binder;
113}
114
115void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
116 std::lock_guard<std::mutex> _l(mLock);
117 mRootObject.clear();
118 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119}
120
121sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000122 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700123 bool hasWeak = mRootObjectWeak.unsafe_get();
124 sp<IBinder> ret = mRootObjectWeak.promote();
125 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
126 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127}
128
Steven Moreland611d15f2021-05-01 01:28:27 +0000129void RpcServer::join() {
Steven Morelandd539fbf2021-05-05 23:40:25 +0000130 while (true) {
131 (void)acceptOne();
132 }
133}
134
135bool RpcServer::acceptOne() {
Steven Morelandf137de92021-04-24 01:54:26 +0000136 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700137 LOG_ALWAYS_FATAL_IF(!hasServer(), "RpcServer must be setup to join.");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000138
139 unique_fd clientFd(
140 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
141
142 if (clientFd < 0) {
143 ALOGE("Could not accept4 socket: %s", strerror(errno));
144 return false;
145 }
146 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
147
Steven Morelandf137de92021-04-24 01:54:26 +0000148 {
149 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandd539fbf2021-05-05 23:40:25 +0000150 std::thread thread =
151 std::thread(&RpcServer::establishConnection, this,
152 std::move(sp<RpcServer>::fromExisting(this)), std::move(clientFd));
153 mConnectingThreads[thread.get_id()] = std::move(thread);
Steven Morelandf137de92021-04-24 01:54:26 +0000154 }
155
Steven Morelandd539fbf2021-05-05 23:40:25 +0000156 return true;
Steven Morelandf137de92021-04-24 01:54:26 +0000157}
158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000160 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000161 std::vector<sp<RpcSession>> sessions;
162 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000163 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000165 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000166 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000167}
168
Steven Morelandd539fbf2021-05-05 23:40:25 +0000169size_t RpcServer::numUninitializedSessions() {
170 std::lock_guard<std::mutex> _l(mLock);
171 return mConnectingThreads.size();
172}
173
Steven Morelanda63ff932021-05-12 00:03:15 +0000174void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
175 LOG_ALWAYS_FATAL_IF(this != server.get(), "Must pass same ownership object");
176
177 // TODO(b/183988761): cannot trust this simple ID
178 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Steven Moreland5802c2b2021-05-12 20:13:04 +0000179 bool idValid = true;
Steven Morelanda63ff932021-05-12 00:03:15 +0000180 int32_t id;
181 if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
182 ALOGE("Could not read ID from fd %d", clientFd.get());
Steven Moreland5802c2b2021-05-12 20:13:04 +0000183 idValid = false;
Steven Morelanda63ff932021-05-12 00:03:15 +0000184 }
185
186 std::thread thisThread;
187 sp<RpcSession> session;
188 {
189 std::lock_guard<std::mutex> _l(mLock);
190
191 auto threadId = mConnectingThreads.find(std::this_thread::get_id());
192 LOG_ALWAYS_FATAL_IF(threadId == mConnectingThreads.end(),
193 "Must establish connection on owned thread");
194 thisThread = std::move(threadId->second);
Steven Moreland5802c2b2021-05-12 20:13:04 +0000195 ScopeGuard detachGuard = [&]() { thisThread.detach(); };
Steven Morelanda63ff932021-05-12 00:03:15 +0000196 mConnectingThreads.erase(threadId);
197
Steven Moreland5802c2b2021-05-12 20:13:04 +0000198 if (!idValid) {
199 return;
200 }
201
Steven Morelanda63ff932021-05-12 00:03:15 +0000202 if (id == RPC_SESSION_ID_NEW) {
203 LOG_ALWAYS_FATAL_IF(mSessionIdCounter >= INT32_MAX, "Out of session IDs");
204 mSessionIdCounter++;
205
206 session = RpcSession::make();
207 session->setForServer(wp<RpcServer>::fromExisting(this), mSessionIdCounter);
208
209 mSessions[mSessionIdCounter] = session;
210 } else {
211 auto it = mSessions.find(id);
212 if (it == mSessions.end()) {
213 ALOGE("Cannot add thread, no record of session with ID %d", id);
214 return;
215 }
216 session = it->second;
217 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000218
219 detachGuard.Disable();
220 session->preJoin(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000221 }
222
223 // avoid strong cycle
224 server = nullptr;
225 //
226 //
227 // DO NOT ACCESS MEMBER VARIABLES BELOW
228 //
229
Steven Moreland5802c2b2021-05-12 20:13:04 +0000230 session->join(std::move(clientFd));
Steven Morelanda63ff932021-05-12 00:03:15 +0000231}
232
Steven Moreland611d15f2021-05-01 01:28:27 +0000233bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000234 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700235 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000236
237 unique_fd serverFd(
238 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
239 if (serverFd == -1) {
240 ALOGE("Could not create socket: %s", strerror(errno));
241 return false;
242 }
243
244 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
245 int savedErrno = errno;
246 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
247 return false;
248 }
249
250 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
251 int savedErrno = errno;
252 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
253 return false;
254 }
255
Steven Moreland704fc1a2021-05-04 23:13:14 +0000256 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
257
Yifan Hongc276f8d2021-05-13 17:13:44 -0700258 if (!setupExternalServer(std::move(serverFd))) {
259 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
260 return false;
261 }
Steven Moreland611d15f2021-05-01 01:28:27 +0000262 return true;
263}
264
Steven Morelandee78e762021-05-05 21:12:51 +0000265void RpcServer::onSessionTerminating(const sp<RpcSession>& session) {
266 auto id = session->mId;
267 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
268 LOG_RPC_DETAIL("Dropping session %d", *id);
269
270 std::lock_guard<std::mutex> _l(mLock);
271 auto it = mSessions.find(*id);
272 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %d", *id);
273 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %d", *id);
274 (void)mSessions.erase(it);
275}
276
Yifan Hong0eb5a672021-05-12 18:00:25 -0700277bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700278 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700279 std::lock_guard<std::mutex> _l(mLock);
280 return mServer.ok();
281}
282
Yifan Hong00aeb762021-05-12 17:07:36 -0700283unique_fd RpcServer::releaseServer() {
284 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
285 std::lock_guard<std::mutex> _l(mLock);
286 return std::move(mServer);
287}
288
289bool RpcServer::setupExternalServer(base::unique_fd serverFd) {
290 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
291 std::lock_guard<std::mutex> _l(mLock);
292 if (mServer.ok()) {
293 ALOGE("Each RpcServer can only have one server.");
294 return false;
295 }
296 mServer = std::move(serverFd);
297 return true;
298}
299
Steven Moreland5553ac42020-11-11 02:14:45 +0000300} // namespace android