blob: 40331bc004dccf041240da5590bde8e301f028d2 [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;
64 LOG_ALWAYS_FATAL_IF(pathLen > sizeof(mAddr.sun_path), "%u %s", pathLen, path);
65 memcpy(mAddr.sun_path, path, pathLen);
66 }
67 virtual ~UnixSocketAddress() {}
68 std::string toString() const override {
69 return String8::format("path '%.*s'", static_cast<int>(sizeof(mAddr.sun_path)),
70 mAddr.sun_path)
71 .c_str();
72 }
73 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
74 size_t addrSize() const override { return sizeof(mAddr); }
75
76private:
77 sockaddr_un mAddr;
78};
79
Steven Moreland5553ac42020-11-11 02:14:45 +000080bool RpcConnection::setupUnixDomainServer(const char* path) {
Steven Morelandd47b32c2021-04-13 02:03:08 +000081 return setupSocketServer(UnixSocketAddress(path));
Steven Moreland5553ac42020-11-11 02:14:45 +000082}
83
84bool RpcConnection::addUnixDomainClient(const char* path) {
Steven Morelandd47b32c2021-04-13 02:03:08 +000085 return addSocketClient(UnixSocketAddress(path));
Steven Moreland53583542021-03-30 00:25:41 +000086}
87
Steven Morelandc1635952021-04-01 16:20:47 +000088#ifdef __BIONIC__
89
90class VsockSocketAddress : public RpcConnection::SocketAddress {
91public:
92 VsockSocketAddress(unsigned int cid, unsigned int port)
93 : mAddr({
94 .svm_family = AF_VSOCK,
95 .svm_port = port,
96 .svm_cid = cid,
97 }) {}
98 virtual ~VsockSocketAddress() {}
99 std::string toString() const override {
100 return String8::format("cid %du port %du", mAddr.svm_cid, mAddr.svm_port).c_str();
101 }
102 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
103 size_t addrSize() const override { return sizeof(mAddr); }
104
105private:
106 sockaddr_vm mAddr;
107};
108
109bool RpcConnection::setupVsockServer(unsigned int port) {
110 // realizing value w/ this type at compile time to avoid ubsan abort
111 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
112
Steven Morelandd47b32c2021-04-13 02:03:08 +0000113 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
Steven Morelandc1635952021-04-01 16:20:47 +0000114}
115
116bool RpcConnection::addVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandd47b32c2021-04-13 02:03:08 +0000117 return addSocketClient(VsockSocketAddress(cid, port));
Steven Morelandc1635952021-04-01 16:20:47 +0000118}
119
120#endif // __BIONIC__
121
Steven Morelandd47b32c2021-04-13 02:03:08 +0000122bool RpcConnection::addNullDebuggingClient() {
123 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
124
125 if (serverFd == -1) {
126 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
127 return false;
128 }
129
130 addClient(std::move(serverFd));
131 return true;
132}
133
Steven Moreland5553ac42020-11-11 02:14:45 +0000134sp<IBinder> RpcConnection::getRootObject() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000135 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT);
136 return state()->getRootObject(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000137}
138
139status_t RpcConnection::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
140 Parcel* reply, uint32_t flags) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000141 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this),
Steven Moreland5553ac42020-11-11 02:14:45 +0000142 (flags & IBinder::FLAG_ONEWAY) ? SocketUse::CLIENT_ASYNC
143 : SocketUse::CLIENT);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000144 return state()->transact(socket.fd(), address, code, data,
145 sp<RpcConnection>::fromExisting(this), reply, flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000146}
147
148status_t RpcConnection::sendDecStrong(const RpcAddress& address) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000149 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT_REFCOUNT);
Steven Moreland5553ac42020-11-11 02:14:45 +0000150 return state()->sendDecStrong(socket.fd(), address);
151}
152
153void RpcConnection::join() {
154 // establish a connection
155 {
Steven Morelandc1635952021-04-01 16:20:47 +0000156 unique_fd clientFd(
157 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, 0 /*length*/, SOCK_CLOEXEC)));
Steven Moreland5553ac42020-11-11 02:14:45 +0000158 if (clientFd < 0) {
159 // If this log becomes confusing, should save more state from setupUnixDomainServer
160 // in order to output here.
161 ALOGE("Could not accept4 socket: %s", strerror(errno));
162 return;
163 }
164
165 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
166
Steven Morelandc1635952021-04-01 16:20:47 +0000167 assignServerToThisThread(std::move(clientFd));
Steven Moreland5553ac42020-11-11 02:14:45 +0000168 }
169
170 // We may not use the connection we just established (two threads might
171 // establish connections for each other), but for now, just use one
172 // server/socket connection.
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000173 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::SERVER);
Steven Moreland5553ac42020-11-11 02:14:45 +0000174
175 while (true) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000176 status_t error =
177 state()->getAndExecuteCommand(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000178
179 if (error != OK) {
180 ALOGI("Binder socket thread closing w/ status %s", statusToString(error).c_str());
181 return;
182 }
183 }
184}
185
186void RpcConnection::setForServer(const wp<RpcServer>& server) {
187 mForServer = server;
188}
189
190wp<RpcServer> RpcConnection::server() {
191 return mForServer;
192}
193
Steven Morelandd47b32c2021-04-13 02:03:08 +0000194bool RpcConnection::setupSocketServer(const SocketAddress& addr) {
Steven Morelandc1635952021-04-01 16:20:47 +0000195 LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcConnection can only have one server.");
196
197 unique_fd serverFd(
198 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
199 if (serverFd == -1) {
200 ALOGE("Could not create socket: %s", strerror(errno));
201 return false;
202 }
203
204 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
205 int savedErrno = errno;
206 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
207 return false;
208 }
209
210 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
211 int savedErrno = errno;
212 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
213 return false;
214 }
215
216 mServer = std::move(serverFd);
217 return true;
Steven Moreland53583542021-03-30 00:25:41 +0000218}
219
Steven Morelandd47b32c2021-04-13 02:03:08 +0000220bool RpcConnection::addSocketClient(const SocketAddress& addr) {
Steven Morelandc1635952021-04-01 16:20:47 +0000221 unique_fd serverFd(
222 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
223 if (serverFd == -1) {
224 int savedErrno = errno;
225 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
226 return false;
227 }
228
229 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
230 int savedErrno = errno;
231 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
232 return false;
233 }
234
235 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
236
Steven Morelandd47b32c2021-04-13 02:03:08 +0000237 addClient(std::move(serverFd));
Steven Morelandc1635952021-04-01 16:20:47 +0000238 return true;
239}
240
Steven Morelandd47b32c2021-04-13 02:03:08 +0000241void RpcConnection::addClient(unique_fd&& fd) {
242 std::lock_guard<std::mutex> _l(mSocketMutex);
243 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
244 connection->fd = std::move(fd);
245 mClients.push_back(connection);
246}
247
248void RpcConnection::assignServerToThisThread(unique_fd&& fd) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000249 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000250 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +0000251 connection->fd = std::move(fd);
252 mServers.push_back(connection);
253}
254
255RpcConnection::ExclusiveSocket::ExclusiveSocket(const sp<RpcConnection>& connection, SocketUse use)
256 : mConnection(connection) {
257 pid_t tid = gettid();
258 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
259
260 mConnection->mWaitingThreads++;
261 while (true) {
262 sp<ConnectionSocket> exclusive;
263 sp<ConnectionSocket> available;
264
265 // CHECK FOR DEDICATED CLIENT SOCKET
266 //
267 // A server/looper should always use a dedicated connection.
268 if (use != SocketUse::SERVER) {
269 findSocket(tid, &exclusive, &available, mConnection->mClients,
270 mConnection->mClientsOffset);
271
272 // WARNING: this assumes a server cannot request its client to send
273 // a transaction, as mServers is excluded below.
274 //
275 // Imagine we have more than one thread in play, and a single thread
276 // sends a synchronous, then an asynchronous command. Imagine the
277 // asynchronous command is sent on the first client socket. Then, if
278 // we naively send a synchronous command to that same socket, the
279 // thread on the far side might be busy processing the asynchronous
280 // command. So, we move to considering the second available thread
281 // for subsequent calls.
282 if (use == SocketUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
283 mConnection->mClientsOffset =
284 (mConnection->mClientsOffset + 1) % mConnection->mClients.size();
285 }
286 }
287
288 // USE SERVING SOCKET (to start serving or for nested transaction)
289 //
290 // asynchronous calls cannot be nested
291 if (use != SocketUse::CLIENT_ASYNC) {
292 // servers should start serving on an available thread only
293 // otherwise, this should only be a nested call
294 bool useAvailable = use == SocketUse::SERVER;
295
296 findSocket(tid, &exclusive, (useAvailable ? &available : nullptr),
297 mConnection->mServers, 0 /* index hint */);
298 }
299
300 // if our thread is already using a connection, prioritize using that
301 if (exclusive != nullptr) {
302 mSocket = exclusive;
303 mReentrant = true;
304 break;
305 } else if (available != nullptr) {
306 mSocket = available;
307 mSocket->exclusiveTid = tid;
308 break;
309 }
310
311 LOG_ALWAYS_FATAL_IF(use == SocketUse::SERVER, "Must create connection to join one.");
312
313 // in regular binder, this would usually be a deadlock :)
314 LOG_ALWAYS_FATAL_IF(mConnection->mClients.size() == 0,
315 "Not a client of any connection. You must create a connection to an "
316 "RPC server to make any non-nested (e.g. oneway or on another thread) "
317 "calls.");
318
319 LOG_RPC_DETAIL("No available connection (have %zu clients and %zu servers). Waiting...",
320 mConnection->mClients.size(), mConnection->mServers.size());
321 mConnection->mSocketCv.wait(_l);
322 }
323 mConnection->mWaitingThreads--;
324}
325
326void RpcConnection::ExclusiveSocket::findSocket(pid_t tid, sp<ConnectionSocket>* exclusive,
327 sp<ConnectionSocket>* available,
328 std::vector<sp<ConnectionSocket>>& sockets,
329 size_t socketsIndexHint) {
330 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
331 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
332
333 if (*exclusive != nullptr) return; // consistent with break below
334
335 for (size_t i = 0; i < sockets.size(); i++) {
336 sp<ConnectionSocket>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
337
338 // take first available connection (intuition = caching)
339 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
340 *available = socket;
341 continue;
342 }
343
344 // though, prefer to take connection which is already inuse by this thread
345 // (nested transactions)
346 if (exclusive && socket->exclusiveTid == tid) {
347 *exclusive = socket;
348 break; // consistent with return above
349 }
350 }
351}
352
353RpcConnection::ExclusiveSocket::~ExclusiveSocket() {
354 // reentrant use of a connection means something less deep in the call stack
355 // is using this fd, and it retains the right to it. So, we don't give up
356 // exclusive ownership, and no thread is freed.
357 if (!mReentrant) {
358 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
359 mSocket->exclusiveTid = std::nullopt;
360 if (mConnection->mWaitingThreads > 0) {
361 _l.unlock();
362 mConnection->mSocketCv.notify_one();
363 }
364 }
365}
366
367} // namespace android