blob: 06c3a4206df01f4dcfdc099f1b13481e8cd1da23 [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);
Steven Moreland5553ac42020-11-11 02:14:45 +0000112 mRootObject = binder;
113}
114
115sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000116 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland5553ac42020-11-11 02:14:45 +0000117 return mRootObject;
118}
119
Steven Moreland611d15f2021-05-01 01:28:27 +0000120void RpcServer::join() {
Steven Morelandf137de92021-04-24 01:54:26 +0000121 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Steven Morelandf137de92021-04-24 01:54:26 +0000122 {
123 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland611d15f2021-05-01 01:28:27 +0000124 LOG_ALWAYS_FATAL_IF(mServer.get() == -1, "RpcServer must be setup to join.");
Steven Morelandf137de92021-04-24 01:54:26 +0000125 }
126
Steven Moreland736664b2021-05-01 04:27:25 +0000127 while (true) {
Yifan Hong00db74d2021-05-07 18:42:46 -0700128 unique_fd clientFd(TEMP_FAILURE_RETRY(
129 accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
Steven Moreland736664b2021-05-01 04:27:25 +0000130
131 if (clientFd < 0) {
132 ALOGE("Could not accept4 socket: %s", strerror(errno));
133 continue;
134 }
135 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
136
Steven Moreland736664b2021-05-01 04:27:25 +0000137 {
138 std::lock_guard<std::mutex> _l(mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000139 std::thread thread =
140 std::thread(&RpcServer::establishConnection, this,
141 std::move(sp<RpcServer>::fromExisting(this)), std::move(clientFd));
142 mConnectingThreads[thread.get_id()] = std::move(thread);
Steven Moreland736664b2021-05-01 04:27:25 +0000143 }
144 }
Steven Morelandf137de92021-04-24 01:54:26 +0000145}
146
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000147std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000148 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149 std::vector<sp<RpcSession>> sessions;
150 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000151 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000152 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000153 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000155}
156
Steven Morelanda63ff932021-05-12 00:03:15 +0000157void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
158 LOG_ALWAYS_FATAL_IF(this != server.get(), "Must pass same ownership object");
159
160 // TODO(b/183988761): cannot trust this simple ID
161 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Steven Moreland5802c2b2021-05-12 20:13:04 +0000162 bool idValid = true;
Steven Morelanda63ff932021-05-12 00:03:15 +0000163 int32_t id;
164 if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
165 ALOGE("Could not read ID from fd %d", clientFd.get());
Steven Moreland5802c2b2021-05-12 20:13:04 +0000166 idValid = false;
Steven Morelanda63ff932021-05-12 00:03:15 +0000167 }
168
169 std::thread thisThread;
170 sp<RpcSession> session;
171 {
172 std::lock_guard<std::mutex> _l(mLock);
173
174 auto threadId = mConnectingThreads.find(std::this_thread::get_id());
175 LOG_ALWAYS_FATAL_IF(threadId == mConnectingThreads.end(),
176 "Must establish connection on owned thread");
177 thisThread = std::move(threadId->second);
Steven Moreland5802c2b2021-05-12 20:13:04 +0000178 ScopeGuard detachGuard = [&]() { thisThread.detach(); };
Steven Morelanda63ff932021-05-12 00:03:15 +0000179 mConnectingThreads.erase(threadId);
180
Steven Moreland5802c2b2021-05-12 20:13:04 +0000181 if (!idValid) {
182 return;
183 }
184
Steven Morelanda63ff932021-05-12 00:03:15 +0000185 if (id == RPC_SESSION_ID_NEW) {
186 LOG_ALWAYS_FATAL_IF(mSessionIdCounter >= INT32_MAX, "Out of session IDs");
187 mSessionIdCounter++;
188
189 session = RpcSession::make();
190 session->setForServer(wp<RpcServer>::fromExisting(this), mSessionIdCounter);
191
192 mSessions[mSessionIdCounter] = session;
193 } else {
194 auto it = mSessions.find(id);
195 if (it == mSessions.end()) {
196 ALOGE("Cannot add thread, no record of session with ID %d", id);
197 return;
198 }
199 session = it->second;
200 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000201
202 detachGuard.Disable();
203 session->preJoin(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000204 }
205
206 // avoid strong cycle
207 server = nullptr;
208 //
209 //
210 // DO NOT ACCESS MEMBER VARIABLES BELOW
211 //
212
Steven Moreland5802c2b2021-05-12 20:13:04 +0000213 session->join(std::move(clientFd));
Steven Morelanda63ff932021-05-12 00:03:15 +0000214}
215
Steven Moreland611d15f2021-05-01 01:28:27 +0000216bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000217 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
218
Steven Moreland611d15f2021-05-01 01:28:27 +0000219 {
220 std::lock_guard<std::mutex> _l(mLock);
221 LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcServer can only have one server.");
222 }
223
224 unique_fd serverFd(
225 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
226 if (serverFd == -1) {
227 ALOGE("Could not create socket: %s", strerror(errno));
228 return false;
229 }
230
231 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
232 int savedErrno = errno;
233 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
234 return false;
235 }
236
237 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
238 int savedErrno = errno;
239 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
240 return false;
241 }
242
Steven Moreland704fc1a2021-05-04 23:13:14 +0000243 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
244
Steven Moreland611d15f2021-05-01 01:28:27 +0000245 mServer = std::move(serverFd);
246 return true;
247}
248
Steven Morelandee78e762021-05-05 21:12:51 +0000249void RpcServer::onSessionTerminating(const sp<RpcSession>& session) {
250 auto id = session->mId;
251 LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
252 LOG_RPC_DETAIL("Dropping session %d", *id);
253
254 std::lock_guard<std::mutex> _l(mLock);
255 auto it = mSessions.find(*id);
256 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %d", *id);
257 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %d", *id);
258 (void)mSessions.erase(it);
259}
260
Steven Moreland5553ac42020-11-11 02:14:45 +0000261} // namespace android