blob: c1ed93a6f0e39764446c35893671ec60d4fe4cc0 [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 "RpcConnection"
18
19#include <binder/RpcConnection.h>
20
21#include <binder/Parcel.h>
22#include <binder/Stability.h>
Steven Morelandc1635952021-04-01 16:20:47 +000023#include <utils/String8.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024
25#include "RpcState.h"
26#include "RpcWireFormat.h"
27
28#include <sys/socket.h>
29#include <sys/types.h>
30#include <sys/un.h>
31#include <unistd.h>
32
Steven Morelandc1635952021-04-01 16:20:47 +000033#ifdef __GLIBC__
Steven Moreland5553ac42020-11-11 02:14:45 +000034extern "C" pid_t gettid();
35#endif
36
Steven Morelandc1635952021-04-01 16:20:47 +000037#ifdef __BIONIC__
38#include <linux/vm_sockets.h>
39#endif
40
Steven Moreland5553ac42020-11-11 02:14:45 +000041namespace android {
42
43using base::unique_fd;
44
Steven Morelandc1635952021-04-01 16:20:47 +000045RpcConnection::SocketAddress::~SocketAddress() {}
46
Steven Moreland5553ac42020-11-11 02:14:45 +000047RpcConnection::RpcConnection() {
48 LOG_RPC_DETAIL("RpcConnection created %p", this);
49
50 mState = std::make_unique<RpcState>();
51}
52RpcConnection::~RpcConnection() {
53 LOG_RPC_DETAIL("RpcConnection destroyed %p", this);
54}
55
56sp<RpcConnection> RpcConnection::make() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +000057 return sp<RpcConnection>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +000058}
59
Steven Morelandc1635952021-04-01 16:20:47 +000060class UnixSocketAddress : public RpcConnection::SocketAddress {
61public:
62 explicit UnixSocketAddress(const char* path) : mAddr({.sun_family = AF_UNIX}) {
63 unsigned int pathLen = strlen(path) + 1;
Steven Morelandcda60852021-04-14 23:45:32 +000064 LOG_ALWAYS_FATAL_IF(pathLen > sizeof(mAddr.sun_path), "Socket path is too long: %u %s",
65 pathLen, path);
Steven Morelandc1635952021-04-01 16:20:47 +000066 memcpy(mAddr.sun_path, path, pathLen);
67 }
68 virtual ~UnixSocketAddress() {}
69 std::string toString() const override {
70 return String8::format("path '%.*s'", static_cast<int>(sizeof(mAddr.sun_path)),
71 mAddr.sun_path)
72 .c_str();
73 }
74 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
75 size_t addrSize() const override { return sizeof(mAddr); }
76
77private:
78 sockaddr_un mAddr;
79};
80
Steven Moreland5553ac42020-11-11 02:14:45 +000081bool RpcConnection::setupUnixDomainServer(const char* path) {
Steven Morelandc1635952021-04-01 16:20:47 +000082 return addServer(UnixSocketAddress(path));
Steven Moreland5553ac42020-11-11 02:14:45 +000083}
84
85bool RpcConnection::addUnixDomainClient(const char* path) {
Steven Morelandc1635952021-04-01 16:20:47 +000086 return addClient(UnixSocketAddress(path));
Steven Moreland53583542021-03-30 00:25:41 +000087}
88
Steven Morelandc1635952021-04-01 16:20:47 +000089#ifdef __BIONIC__
90
91class VsockSocketAddress : public RpcConnection::SocketAddress {
92public:
93 VsockSocketAddress(unsigned int cid, unsigned int port)
94 : mAddr({
95 .svm_family = AF_VSOCK,
96 .svm_port = port,
97 .svm_cid = cid,
98 }) {}
99 virtual ~VsockSocketAddress() {}
100 std::string toString() const override {
101 return String8::format("cid %du port %du", mAddr.svm_cid, mAddr.svm_port).c_str();
102 }
103 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
104 size_t addrSize() const override { return sizeof(mAddr); }
105
106private:
107 sockaddr_vm mAddr;
108};
109
110bool RpcConnection::setupVsockServer(unsigned int port) {
111 // realizing value w/ this type at compile time to avoid ubsan abort
112 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
113
114 return addServer(VsockSocketAddress(kAnyCid, port));
115}
116
117bool RpcConnection::addVsockClient(unsigned int cid, unsigned int port) {
118 return addClient(VsockSocketAddress(cid, port));
119}
120
121#endif // __BIONIC__
122
Steven Moreland5553ac42020-11-11 02:14:45 +0000123sp<IBinder> RpcConnection::getRootObject() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000124 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT);
125 return state()->getRootObject(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000126}
127
128status_t RpcConnection::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
129 Parcel* reply, uint32_t flags) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000130 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this),
Steven Moreland5553ac42020-11-11 02:14:45 +0000131 (flags & IBinder::FLAG_ONEWAY) ? SocketUse::CLIENT_ASYNC
132 : SocketUse::CLIENT);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000133 return state()->transact(socket.fd(), address, code, data,
134 sp<RpcConnection>::fromExisting(this), reply, flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000135}
136
137status_t RpcConnection::sendDecStrong(const RpcAddress& address) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000138 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT_REFCOUNT);
Steven Moreland5553ac42020-11-11 02:14:45 +0000139 return state()->sendDecStrong(socket.fd(), address);
140}
141
142void RpcConnection::join() {
143 // establish a connection
144 {
Steven Morelandc1635952021-04-01 16:20:47 +0000145 unique_fd clientFd(
146 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, 0 /*length*/, SOCK_CLOEXEC)));
Steven Moreland5553ac42020-11-11 02:14:45 +0000147 if (clientFd < 0) {
148 // If this log becomes confusing, should save more state from setupUnixDomainServer
149 // in order to output here.
150 ALOGE("Could not accept4 socket: %s", strerror(errno));
151 return;
152 }
153
154 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
155
Steven Morelandc1635952021-04-01 16:20:47 +0000156 assignServerToThisThread(std::move(clientFd));
Steven Moreland5553ac42020-11-11 02:14:45 +0000157 }
158
159 // We may not use the connection we just established (two threads might
160 // establish connections for each other), but for now, just use one
161 // server/socket connection.
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000162 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::SERVER);
Steven Moreland5553ac42020-11-11 02:14:45 +0000163
164 while (true) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000165 status_t error =
166 state()->getAndExecuteCommand(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000167
168 if (error != OK) {
169 ALOGI("Binder socket thread closing w/ status %s", statusToString(error).c_str());
170 return;
171 }
172 }
173}
174
175void RpcConnection::setForServer(const wp<RpcServer>& server) {
176 mForServer = server;
177}
178
179wp<RpcServer> RpcConnection::server() {
180 return mForServer;
181}
182
Steven Morelandc1635952021-04-01 16:20:47 +0000183bool RpcConnection::addServer(const SocketAddress& addr) {
184 LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcConnection can only have one server.");
185
186 unique_fd serverFd(
187 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
188 if (serverFd == -1) {
189 ALOGE("Could not create socket: %s", strerror(errno));
190 return false;
191 }
192
193 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
194 int savedErrno = errno;
195 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
196 return false;
197 }
198
199 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
200 int savedErrno = errno;
201 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
202 return false;
203 }
204
205 mServer = std::move(serverFd);
206 return true;
Steven Moreland53583542021-03-30 00:25:41 +0000207}
208
Steven Morelandc1635952021-04-01 16:20:47 +0000209bool RpcConnection::addClient(const SocketAddress& addr) {
210 unique_fd serverFd(
211 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
212 if (serverFd == -1) {
213 int savedErrno = errno;
214 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
215 return false;
216 }
217
218 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
219 int savedErrno = errno;
220 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
221 return false;
222 }
223
224 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
225
226 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000227 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Morelandc1635952021-04-01 16:20:47 +0000228 connection->fd = std::move(serverFd);
229 mClients.push_back(connection);
230 return true;
231}
232
233void RpcConnection::assignServerToThisThread(base::unique_fd&& fd) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000234 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000235 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +0000236 connection->fd = std::move(fd);
237 mServers.push_back(connection);
238}
239
240RpcConnection::ExclusiveSocket::ExclusiveSocket(const sp<RpcConnection>& connection, SocketUse use)
241 : mConnection(connection) {
242 pid_t tid = gettid();
243 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
244
245 mConnection->mWaitingThreads++;
246 while (true) {
247 sp<ConnectionSocket> exclusive;
248 sp<ConnectionSocket> available;
249
250 // CHECK FOR DEDICATED CLIENT SOCKET
251 //
252 // A server/looper should always use a dedicated connection.
253 if (use != SocketUse::SERVER) {
254 findSocket(tid, &exclusive, &available, mConnection->mClients,
255 mConnection->mClientsOffset);
256
257 // WARNING: this assumes a server cannot request its client to send
258 // a transaction, as mServers is excluded below.
259 //
260 // Imagine we have more than one thread in play, and a single thread
261 // sends a synchronous, then an asynchronous command. Imagine the
262 // asynchronous command is sent on the first client socket. Then, if
263 // we naively send a synchronous command to that same socket, the
264 // thread on the far side might be busy processing the asynchronous
265 // command. So, we move to considering the second available thread
266 // for subsequent calls.
267 if (use == SocketUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
268 mConnection->mClientsOffset =
269 (mConnection->mClientsOffset + 1) % mConnection->mClients.size();
270 }
271 }
272
273 // USE SERVING SOCKET (to start serving or for nested transaction)
274 //
275 // asynchronous calls cannot be nested
276 if (use != SocketUse::CLIENT_ASYNC) {
277 // servers should start serving on an available thread only
278 // otherwise, this should only be a nested call
279 bool useAvailable = use == SocketUse::SERVER;
280
281 findSocket(tid, &exclusive, (useAvailable ? &available : nullptr),
282 mConnection->mServers, 0 /* index hint */);
283 }
284
285 // if our thread is already using a connection, prioritize using that
286 if (exclusive != nullptr) {
287 mSocket = exclusive;
288 mReentrant = true;
289 break;
290 } else if (available != nullptr) {
291 mSocket = available;
292 mSocket->exclusiveTid = tid;
293 break;
294 }
295
296 LOG_ALWAYS_FATAL_IF(use == SocketUse::SERVER, "Must create connection to join one.");
297
298 // in regular binder, this would usually be a deadlock :)
299 LOG_ALWAYS_FATAL_IF(mConnection->mClients.size() == 0,
300 "Not a client of any connection. You must create a connection to an "
301 "RPC server to make any non-nested (e.g. oneway or on another thread) "
302 "calls.");
303
304 LOG_RPC_DETAIL("No available connection (have %zu clients and %zu servers). Waiting...",
305 mConnection->mClients.size(), mConnection->mServers.size());
306 mConnection->mSocketCv.wait(_l);
307 }
308 mConnection->mWaitingThreads--;
309}
310
311void RpcConnection::ExclusiveSocket::findSocket(pid_t tid, sp<ConnectionSocket>* exclusive,
312 sp<ConnectionSocket>* available,
313 std::vector<sp<ConnectionSocket>>& sockets,
314 size_t socketsIndexHint) {
315 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
316 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
317
318 if (*exclusive != nullptr) return; // consistent with break below
319
320 for (size_t i = 0; i < sockets.size(); i++) {
321 sp<ConnectionSocket>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
322
323 // take first available connection (intuition = caching)
324 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
325 *available = socket;
326 continue;
327 }
328
329 // though, prefer to take connection which is already inuse by this thread
330 // (nested transactions)
331 if (exclusive && socket->exclusiveTid == tid) {
332 *exclusive = socket;
333 break; // consistent with return above
334 }
335 }
336}
337
338RpcConnection::ExclusiveSocket::~ExclusiveSocket() {
339 // reentrant use of a connection means something less deep in the call stack
340 // is using this fd, and it retains the right to it. So, we don't give up
341 // exclusive ownership, and no thread is freed.
342 if (!mReentrant) {
343 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
344 mSocket->exclusiveTid = std::nullopt;
345 if (mConnection->mWaitingThreads > 0) {
346 _l.unlock();
347 mConnection->mSocketCv.notify_one();
348 }
349 }
350}
351
352} // namespace android