blob: 1388a801e4854c33d01a6169f6c39588975c29f2 [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
Yifan Hong0d2bd112021-04-13 17:38:36 -070021#include <arpa/inet.h>
22#include <netdb.h>
23#include <netinet/in.h>
24#include <sys/socket.h>
25#include <sys/types.h>
26#include <sys/un.h>
27#include <unistd.h>
28
29#include <string_view>
30
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <binder/Parcel.h>
32#include <binder/Stability.h>
Steven Morelandc1635952021-04-01 16:20:47 +000033#include <utils/String8.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034
35#include "RpcState.h"
36#include "RpcWireFormat.h"
37
Steven Morelandc1635952021-04-01 16:20:47 +000038#ifdef __GLIBC__
Steven Moreland5553ac42020-11-11 02:14:45 +000039extern "C" pid_t gettid();
40#endif
41
Steven Morelandc1635952021-04-01 16:20:47 +000042#ifdef __BIONIC__
43#include <linux/vm_sockets.h>
44#endif
45
Steven Moreland5553ac42020-11-11 02:14:45 +000046namespace android {
47
48using base::unique_fd;
Yifan Hong0d2bd112021-04-13 17:38:36 -070049using AddrInfo = std::unique_ptr<addrinfo, decltype(&freeaddrinfo)>;
Steven Moreland5553ac42020-11-11 02:14:45 +000050
Steven Morelandc1635952021-04-01 16:20:47 +000051RpcConnection::SocketAddress::~SocketAddress() {}
52
Steven Moreland5553ac42020-11-11 02:14:45 +000053RpcConnection::RpcConnection() {
54 LOG_RPC_DETAIL("RpcConnection created %p", this);
55
56 mState = std::make_unique<RpcState>();
57}
58RpcConnection::~RpcConnection() {
59 LOG_RPC_DETAIL("RpcConnection destroyed %p", this);
Steven Morelandaf816d82021-04-19 23:11:33 +000060
61 std::lock_guard<std::mutex> _l(mSocketMutex);
62 LOG_ALWAYS_FATAL_IF(mServers.size() != 0,
63 "Should not be able to destroy a connection with servers in use.");
Steven Moreland5553ac42020-11-11 02:14:45 +000064}
65
66sp<RpcConnection> RpcConnection::make() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +000067 return sp<RpcConnection>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +000068}
69
Steven Morelandc1635952021-04-01 16:20:47 +000070class UnixSocketAddress : public RpcConnection::SocketAddress {
71public:
72 explicit UnixSocketAddress(const char* path) : mAddr({.sun_family = AF_UNIX}) {
73 unsigned int pathLen = strlen(path) + 1;
Steven Morelandcda60852021-04-14 23:45:32 +000074 LOG_ALWAYS_FATAL_IF(pathLen > sizeof(mAddr.sun_path), "Socket path is too long: %u %s",
75 pathLen, path);
Steven Morelandc1635952021-04-01 16:20:47 +000076 memcpy(mAddr.sun_path, path, pathLen);
77 }
78 virtual ~UnixSocketAddress() {}
79 std::string toString() const override {
80 return String8::format("path '%.*s'", static_cast<int>(sizeof(mAddr.sun_path)),
81 mAddr.sun_path)
82 .c_str();
83 }
84 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
85 size_t addrSize() const override { return sizeof(mAddr); }
86
87private:
88 sockaddr_un mAddr;
89};
90
Steven Moreland5553ac42020-11-11 02:14:45 +000091bool RpcConnection::setupUnixDomainServer(const char* path) {
Steven Morelandd47b32c2021-04-13 02:03:08 +000092 return setupSocketServer(UnixSocketAddress(path));
Steven Moreland5553ac42020-11-11 02:14:45 +000093}
94
95bool RpcConnection::addUnixDomainClient(const char* path) {
Steven Morelandd47b32c2021-04-13 02:03:08 +000096 return addSocketClient(UnixSocketAddress(path));
Steven Moreland53583542021-03-30 00:25:41 +000097}
98
Steven Morelandc1635952021-04-01 16:20:47 +000099#ifdef __BIONIC__
100
101class VsockSocketAddress : public RpcConnection::SocketAddress {
102public:
103 VsockSocketAddress(unsigned int cid, unsigned int port)
104 : mAddr({
105 .svm_family = AF_VSOCK,
106 .svm_port = port,
107 .svm_cid = cid,
108 }) {}
109 virtual ~VsockSocketAddress() {}
110 std::string toString() const override {
Yifan Hong4c791532021-04-14 12:38:46 -0700111 return String8::format("cid %u port %u", mAddr.svm_cid, mAddr.svm_port).c_str();
Steven Morelandc1635952021-04-01 16:20:47 +0000112 }
113 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
114 size_t addrSize() const override { return sizeof(mAddr); }
115
116private:
117 sockaddr_vm mAddr;
118};
119
120bool RpcConnection::setupVsockServer(unsigned int port) {
121 // realizing value w/ this type at compile time to avoid ubsan abort
122 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
123
Steven Morelandd47b32c2021-04-13 02:03:08 +0000124 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
Steven Morelandc1635952021-04-01 16:20:47 +0000125}
126
127bool RpcConnection::addVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandd47b32c2021-04-13 02:03:08 +0000128 return addSocketClient(VsockSocketAddress(cid, port));
Steven Morelandc1635952021-04-01 16:20:47 +0000129}
130
131#endif // __BIONIC__
132
Yifan Hong0d2bd112021-04-13 17:38:36 -0700133class SocketAddressImpl : public RpcConnection::SocketAddress {
134public:
135 SocketAddressImpl(const sockaddr* addr, size_t size, const String8& desc)
136 : mAddr(addr), mSize(size), mDesc(desc) {}
137 [[nodiscard]] std::string toString() const override {
138 return std::string(mDesc.c_str(), mDesc.size());
139 }
140 [[nodiscard]] const sockaddr* addr() const override { return mAddr; }
141 [[nodiscard]] size_t addrSize() const override { return mSize; }
142 void set(const sockaddr* addr, size_t size) {
143 mAddr = addr;
144 mSize = size;
145 }
146
147private:
148 const sockaddr* mAddr = nullptr;
149 size_t mSize = 0;
150 String8 mDesc;
151};
152
153AddrInfo GetAddrInfo(const char* addr, unsigned int port) {
154 addrinfo hint{
155 .ai_flags = 0,
156 .ai_family = AF_UNSPEC,
157 .ai_socktype = SOCK_STREAM,
158 .ai_protocol = 0,
159 };
160 addrinfo* aiStart = nullptr;
161 if (int rc = getaddrinfo(addr, std::to_string(port).data(), &hint, &aiStart); 0 != rc) {
162 ALOGE("Unable to resolve %s:%u: %s", addr, port, gai_strerror(rc));
163 return AddrInfo(nullptr, nullptr);
164 }
165 if (aiStart == nullptr) {
166 ALOGE("Unable to resolve %s:%u: getaddrinfo returns null", addr, port);
167 return AddrInfo(nullptr, nullptr);
168 }
169 return AddrInfo(aiStart, &freeaddrinfo);
170}
171
172bool RpcConnection::setupInetServer(unsigned int port) {
173 auto aiStart = GetAddrInfo("127.0.0.1", port);
174 if (aiStart == nullptr) return false;
175 SocketAddressImpl socketAddress(nullptr, 0, String8::format("127.0.0.1:%u", port));
176 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
177 socketAddress.set(ai->ai_addr, ai->ai_addrlen);
178 if (setupSocketServer(socketAddress)) return true;
179 }
180 ALOGE("None of the socket address resolved for 127.0.0.1:%u can be set up as inet server.",
181 port);
182 return false;
183}
184
185bool RpcConnection::addInetClient(const char* addr, unsigned int port) {
186 auto aiStart = GetAddrInfo(addr, port);
187 if (aiStart == nullptr) return false;
188 SocketAddressImpl socketAddress(nullptr, 0, String8::format("%s:%u", addr, port));
189 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
190 socketAddress.set(ai->ai_addr, ai->ai_addrlen);
191 if (addSocketClient(socketAddress)) return true;
192 }
193 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
194 return false;
195}
196
Steven Morelandd47b32c2021-04-13 02:03:08 +0000197bool RpcConnection::addNullDebuggingClient() {
198 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
199
200 if (serverFd == -1) {
201 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
202 return false;
203 }
204
205 addClient(std::move(serverFd));
206 return true;
207}
208
Steven Moreland5553ac42020-11-11 02:14:45 +0000209sp<IBinder> RpcConnection::getRootObject() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000210 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT);
211 return state()->getRootObject(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000212}
213
214status_t RpcConnection::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
215 Parcel* reply, uint32_t flags) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000216 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this),
Steven Moreland5553ac42020-11-11 02:14:45 +0000217 (flags & IBinder::FLAG_ONEWAY) ? SocketUse::CLIENT_ASYNC
218 : SocketUse::CLIENT);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000219 return state()->transact(socket.fd(), address, code, data,
220 sp<RpcConnection>::fromExisting(this), reply, flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000221}
222
223status_t RpcConnection::sendDecStrong(const RpcAddress& address) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000224 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT_REFCOUNT);
Steven Moreland5553ac42020-11-11 02:14:45 +0000225 return state()->sendDecStrong(socket.fd(), address);
226}
227
228void RpcConnection::join() {
Steven Morelandaf816d82021-04-19 23:11:33 +0000229 // TODO(b/185167543): do this dynamically, instead of from a static number
230 // of threads
231 unique_fd clientFd(
232 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, 0 /*length*/, SOCK_CLOEXEC)));
233 if (clientFd < 0) {
234 // If this log becomes confusing, should save more state from setupUnixDomainServer
235 // in order to output here.
236 ALOGE("Could not accept4 socket: %s", strerror(errno));
237 return;
Steven Moreland5553ac42020-11-11 02:14:45 +0000238 }
239
Steven Morelandaf816d82021-04-19 23:11:33 +0000240 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
241
242 // must be registered to allow arbitrary client code executing commands to
243 // be able to do nested calls (we can't only read from it)
244 sp<ConnectionSocket> socket = assignServerToThisThread(std::move(clientFd));
Steven Moreland5553ac42020-11-11 02:14:45 +0000245
246 while (true) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000247 status_t error =
Steven Morelandaf816d82021-04-19 23:11:33 +0000248 state()->getAndExecuteCommand(socket->fd, sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000249
250 if (error != OK) {
251 ALOGI("Binder socket thread closing w/ status %s", statusToString(error).c_str());
Steven Morelandaf816d82021-04-19 23:11:33 +0000252 break;
Steven Moreland5553ac42020-11-11 02:14:45 +0000253 }
254 }
Steven Morelandaf816d82021-04-19 23:11:33 +0000255
256 LOG_ALWAYS_FATAL_IF(!removeServerSocket(socket),
257 "bad state: socket object guaranteed to be in list");
Steven Moreland5553ac42020-11-11 02:14:45 +0000258}
259
260void RpcConnection::setForServer(const wp<RpcServer>& server) {
261 mForServer = server;
262}
263
264wp<RpcServer> RpcConnection::server() {
265 return mForServer;
266}
267
Steven Morelandd47b32c2021-04-13 02:03:08 +0000268bool RpcConnection::setupSocketServer(const SocketAddress& addr) {
Steven Morelandc1635952021-04-01 16:20:47 +0000269 LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcConnection can only have one server.");
270
271 unique_fd serverFd(
272 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
273 if (serverFd == -1) {
274 ALOGE("Could not create socket: %s", strerror(errno));
275 return false;
276 }
277
278 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
279 int savedErrno = errno;
280 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
281 return false;
282 }
283
284 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
285 int savedErrno = errno;
286 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
287 return false;
288 }
289
290 mServer = std::move(serverFd);
291 return true;
Steven Moreland53583542021-03-30 00:25:41 +0000292}
293
Steven Morelandd47b32c2021-04-13 02:03:08 +0000294bool RpcConnection::addSocketClient(const SocketAddress& addr) {
Steven Morelandc1635952021-04-01 16:20:47 +0000295 unique_fd serverFd(
296 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
297 if (serverFd == -1) {
298 int savedErrno = errno;
299 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
300 return false;
301 }
302
303 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
304 int savedErrno = errno;
305 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
306 return false;
307 }
308
309 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
310
Steven Morelandd47b32c2021-04-13 02:03:08 +0000311 addClient(std::move(serverFd));
Steven Morelandc1635952021-04-01 16:20:47 +0000312 return true;
313}
314
Steven Morelandd47b32c2021-04-13 02:03:08 +0000315void RpcConnection::addClient(unique_fd&& fd) {
316 std::lock_guard<std::mutex> _l(mSocketMutex);
317 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
318 connection->fd = std::move(fd);
319 mClients.push_back(connection);
320}
321
Steven Morelandaf816d82021-04-19 23:11:33 +0000322sp<RpcConnection::ConnectionSocket> RpcConnection::assignServerToThisThread(unique_fd&& fd) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000323 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000324 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +0000325 connection->fd = std::move(fd);
Steven Morelandaf816d82021-04-19 23:11:33 +0000326 connection->exclusiveTid = gettid();
Steven Moreland5553ac42020-11-11 02:14:45 +0000327 mServers.push_back(connection);
Steven Morelandaf816d82021-04-19 23:11:33 +0000328
329 return connection;
330}
331
332bool RpcConnection::removeServerSocket(const sp<ConnectionSocket>& socket) {
333 std::lock_guard<std::mutex> _l(mSocketMutex);
334 if (auto it = std::find(mServers.begin(), mServers.end(), socket); it != mServers.end()) {
335 mServers.erase(it);
336 return true;
337 }
338 return false;
Steven Moreland5553ac42020-11-11 02:14:45 +0000339}
340
341RpcConnection::ExclusiveSocket::ExclusiveSocket(const sp<RpcConnection>& connection, SocketUse use)
342 : mConnection(connection) {
343 pid_t tid = gettid();
344 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
345
346 mConnection->mWaitingThreads++;
347 while (true) {
348 sp<ConnectionSocket> exclusive;
349 sp<ConnectionSocket> available;
350
351 // CHECK FOR DEDICATED CLIENT SOCKET
352 //
Steven Morelandaf816d82021-04-19 23:11:33 +0000353 // A server/looper should always use a dedicated connection if available
354 findSocket(tid, &exclusive, &available, mConnection->mClients, mConnection->mClientsOffset);
Steven Moreland5553ac42020-11-11 02:14:45 +0000355
Steven Morelandaf816d82021-04-19 23:11:33 +0000356 // WARNING: this assumes a server cannot request its client to send
357 // a transaction, as mServers is excluded below.
358 //
359 // Imagine we have more than one thread in play, and a single thread
360 // sends a synchronous, then an asynchronous command. Imagine the
361 // asynchronous command is sent on the first client socket. Then, if
362 // we naively send a synchronous command to that same socket, the
363 // thread on the far side might be busy processing the asynchronous
364 // command. So, we move to considering the second available thread
365 // for subsequent calls.
366 if (use == SocketUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
367 mConnection->mClientsOffset =
368 (mConnection->mClientsOffset + 1) % mConnection->mClients.size();
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 }
370
Steven Morelandaf816d82021-04-19 23:11:33 +0000371 // USE SERVING SOCKET (for nested transaction)
Steven Moreland5553ac42020-11-11 02:14:45 +0000372 //
373 // asynchronous calls cannot be nested
374 if (use != SocketUse::CLIENT_ASYNC) {
Steven Morelandaf816d82021-04-19 23:11:33 +0000375 // server sockets are always assigned to a thread
376 findSocket(tid, &exclusive, nullptr /*available*/, mConnection->mServers,
377 0 /* index hint */);
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 }
379
380 // if our thread is already using a connection, prioritize using that
381 if (exclusive != nullptr) {
382 mSocket = exclusive;
383 mReentrant = true;
384 break;
385 } else if (available != nullptr) {
386 mSocket = available;
387 mSocket->exclusiveTid = tid;
388 break;
389 }
390
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 // in regular binder, this would usually be a deadlock :)
392 LOG_ALWAYS_FATAL_IF(mConnection->mClients.size() == 0,
393 "Not a client of any connection. You must create a connection to an "
394 "RPC server to make any non-nested (e.g. oneway or on another thread) "
395 "calls.");
396
397 LOG_RPC_DETAIL("No available connection (have %zu clients and %zu servers). Waiting...",
398 mConnection->mClients.size(), mConnection->mServers.size());
399 mConnection->mSocketCv.wait(_l);
400 }
401 mConnection->mWaitingThreads--;
402}
403
404void RpcConnection::ExclusiveSocket::findSocket(pid_t tid, sp<ConnectionSocket>* exclusive,
405 sp<ConnectionSocket>* available,
406 std::vector<sp<ConnectionSocket>>& sockets,
407 size_t socketsIndexHint) {
408 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
409 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
410
411 if (*exclusive != nullptr) return; // consistent with break below
412
413 for (size_t i = 0; i < sockets.size(); i++) {
414 sp<ConnectionSocket>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
415
416 // take first available connection (intuition = caching)
417 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
418 *available = socket;
419 continue;
420 }
421
422 // though, prefer to take connection which is already inuse by this thread
423 // (nested transactions)
424 if (exclusive && socket->exclusiveTid == tid) {
425 *exclusive = socket;
426 break; // consistent with return above
427 }
428 }
429}
430
431RpcConnection::ExclusiveSocket::~ExclusiveSocket() {
432 // reentrant use of a connection means something less deep in the call stack
433 // is using this fd, and it retains the right to it. So, we don't give up
434 // exclusive ownership, and no thread is freed.
435 if (!mReentrant) {
436 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
437 mSocket->exclusiveTid = std::nullopt;
438 if (mConnection->mWaitingThreads > 0) {
439 _l.unlock();
440 mConnection->mSocketCv.notify_one();
441 }
442 }
443}
444
445} // namespace android