blob: 771d738579832cceabaaa2ddde3f719f717723c2 [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +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 "RpcSession"
18
19#include <binder/RpcSession.h>
20
21#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000022#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000023#include <unistd.h>
24
25#include <string_view>
26
Steven Moreland4ec3c432021-05-20 00:32:47 +000027#include <android-base/macros.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000028#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000029#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000030#include <binder/Stability.h>
31#include <utils/String8.h>
32
33#include "RpcSocketAddress.h"
34#include "RpcState.h"
35#include "RpcWireFormat.h"
36
37#ifdef __GLIBC__
38extern "C" pid_t gettid();
39#endif
40
41namespace android {
42
43using base::unique_fd;
44
45RpcSession::RpcSession() {
46 LOG_RPC_DETAIL("RpcSession created %p", this);
47
48 mState = std::make_unique<RpcState>();
49}
50RpcSession::~RpcSession() {
51 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
52
53 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +000054 LOG_ALWAYS_FATAL_IF(mServerConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055 "Should not be able to destroy a session with servers in use.");
56}
57
58sp<RpcSession> RpcSession::make() {
59 return sp<RpcSession>::make();
60}
61
62bool RpcSession::setupUnixDomainClient(const char* path) {
63 return setupSocketClient(UnixSocketAddress(path));
64}
65
Steven Morelandbdb53ab2021-05-05 17:57:41 +000066bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
67 return setupSocketClient(VsockSocketAddress(cid, port));
68}
69
Steven Morelandbdb53ab2021-05-05 17:57:41 +000070bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
71 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
72 if (aiStart == nullptr) return false;
73 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
74 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
75 if (setupSocketClient(socketAddress)) return true;
76 }
77 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
78 return false;
79}
80
81bool RpcSession::addNullDebuggingClient() {
82 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
83
84 if (serverFd == -1) {
85 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
86 return false;
87 }
88
Steven Morelandc8c256b2021-05-11 22:59:09 +000089 addClientConnection(std::move(serverFd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000090 return true;
91}
92
93sp<IBinder> RpcSession::getRootObject() {
94 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
95 return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
96}
97
Steven Moreland1be91352021-05-11 22:12:15 +000098status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000099 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
100 return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
101}
102
103status_t RpcSession::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
104 Parcel* reply, uint32_t flags) {
105 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
106 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
107 : ConnectionUse::CLIENT);
108 return state()->transact(connection.fd(), address, code, data,
109 sp<RpcSession>::fromExisting(this), reply, flags);
110}
111
112status_t RpcSession::sendDecStrong(const RpcAddress& address) {
113 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
114 ConnectionUse::CLIENT_REFCOUNT);
115 return state()->sendDecStrong(connection.fd(), address);
116}
117
Steven Morelande47511f2021-05-20 00:07:41 +0000118std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
119 auto ret = std::make_unique<RpcSession::FdTrigger>();
120 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) return nullptr;
121 return ret;
122}
123
124void RpcSession::FdTrigger::trigger() {
125 mWrite.reset();
126}
127
Steven Moreland4ec3c432021-05-20 00:32:47 +0000128bool RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
129 while (true) {
130 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN, .revents = 0},
131 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
132 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
133 if (ret < 0) {
134 ALOGE("Could not poll: %s", strerror(errno));
135 continue;
136 }
137 if (ret == 0) {
138 continue;
139 }
140 if (pfd[1].revents & POLLHUP) {
141 return false;
142 }
143 return true;
144 }
145}
146
Steven Moreland9d11b922021-05-20 01:22:58 +0000147bool RpcSession::FdTrigger::interruptableRecv(base::borrowed_fd fd, void* data, size_t size) {
148 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
149 uint8_t* end = buffer + size;
150
151 while (triggerablePollRead(fd)) {
152 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
153 if (readSize < 0) {
154 ALOGE("Failed to read %s", strerror(errno));
155 return false;
156 }
157 buffer += readSize;
158 if (buffer == end) return true;
159 }
160 return false;
161}
162
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000163status_t RpcSession::readId() {
164 {
165 std::lock_guard<std::mutex> _l(mMutex);
166 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
167 }
168
169 int32_t id;
170
171 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
172 status_t status =
173 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
174 if (status != OK) return status;
175
176 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
177 mId = id;
178 return OK;
179}
180
Steven Moreland5802c2b2021-05-12 20:13:04 +0000181void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000182 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183
Steven Morelanda63ff932021-05-12 00:03:15 +0000184 {
185 std::lock_guard<std::mutex> _l(mMutex);
186 mThreads[thread.get_id()] = std::move(thread);
187 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000188}
Steven Morelanda63ff932021-05-12 00:03:15 +0000189
Steven Moreland5802c2b2021-05-12 20:13:04 +0000190void RpcSession::join(unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 // must be registered to allow arbitrary client code executing commands to
192 // be able to do nested calls (we can't only read from it)
193 sp<RpcConnection> connection = assignServerToThisThread(std::move(client));
194
195 while (true) {
196 status_t error =
197 state()->getAndExecuteCommand(connection->fd, sp<RpcSession>::fromExisting(this));
198
199 if (error != OK) {
200 ALOGI("Binder connection thread closing w/ status %s", statusToString(error).c_str());
201 break;
202 }
203 }
204
205 LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
206 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000207
208 {
209 std::lock_guard<std::mutex> _l(mMutex);
210 auto it = mThreads.find(std::this_thread::get_id());
211 LOG_ALWAYS_FATAL_IF(it == mThreads.end());
212 it->second.detach();
213 mThreads.erase(it);
214 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215}
216
Steven Morelandee78e762021-05-05 21:12:51 +0000217void RpcSession::terminateLocked() {
218 // TODO(b/185167543):
219 // - kindly notify other side of the connection of termination (can't be
220 // locked)
221 // - prevent new client/servers from being added
222 // - stop all threads which are currently reading/writing
223 // - terminate RpcState?
224
225 if (mTerminated) return;
226
227 sp<RpcServer> server = mForServer.promote();
228 if (server) {
229 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
230 }
231}
232
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000233wp<RpcServer> RpcSession::server() {
234 return mForServer;
235}
236
237bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
238 {
239 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000240 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000242 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000243 }
244
245 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
246
247 // TODO(b/185167543): we should add additional sessions dynamically
248 // instead of all at once.
249 // TODO(b/186470974): first risk of blocking
250 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000251 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
253 statusToString(status).c_str());
254 return false;
255 }
256
257 if (status_t status = readId(); status != OK) {
258 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
259 statusToString(status).c_str());
260 return false;
261 }
262
263 // we've already setup one client
264 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000265 // TODO(b/185167543): shutdown existing connections?
266 if (!setupOneSocketClient(addr, mId.value())) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267 }
268
269 return true;
270}
271
272bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000273 for (size_t tries = 0; tries < 5; tries++) {
274 if (tries > 0) usleep(10000);
275
276 unique_fd serverFd(
277 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
278 if (serverFd == -1) {
279 int savedErrno = errno;
280 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
281 strerror(savedErrno));
282 return false;
283 }
284
285 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
286 if (errno == ECONNRESET) {
287 ALOGW("Connection reset on %s", addr.toString().c_str());
288 continue;
289 }
290 int savedErrno = errno;
291 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
292 strerror(savedErrno));
293 return false;
294 }
295
296 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
297 int savedErrno = errno;
298 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
299 strerror(savedErrno));
300 return false;
301 }
302
303 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
304
Steven Morelandc8c256b2021-05-11 22:59:09 +0000305 addClientConnection(std::move(serverFd));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000306 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 }
308
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000309 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
310 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311}
312
Steven Morelandc8c256b2021-05-11 22:59:09 +0000313void RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314 std::lock_guard<std::mutex> _l(mMutex);
315 sp<RpcConnection> session = sp<RpcConnection>::make();
316 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000317 mClientConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318}
319
320void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
321 mId = sessionId;
322 mForServer = server;
323}
324
325sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
326 std::lock_guard<std::mutex> _l(mMutex);
327 sp<RpcConnection> session = sp<RpcConnection>::make();
328 session->fd = std::move(fd);
329 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000330 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000331
332 return session;
333}
334
335bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
336 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000337 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
338 it != mServerConnections.end()) {
339 mServerConnections.erase(it);
340 if (mServerConnections.size() == 0) {
Steven Morelandee78e762021-05-05 21:12:51 +0000341 terminateLocked();
342 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000343 return true;
344 }
345 return false;
346}
347
348RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
349 ConnectionUse use)
350 : mSession(session) {
351 pid_t tid = gettid();
352 std::unique_lock<std::mutex> _l(mSession->mMutex);
353
354 mSession->mWaitingThreads++;
355 while (true) {
356 sp<RpcConnection> exclusive;
357 sp<RpcConnection> available;
358
359 // CHECK FOR DEDICATED CLIENT SOCKET
360 //
361 // A server/looper should always use a dedicated session if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000362 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
363 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000364
365 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000366 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000367 //
368 // Imagine we have more than one thread in play, and a single thread
369 // sends a synchronous, then an asynchronous command. Imagine the
370 // asynchronous command is sent on the first client connection. Then, if
371 // we naively send a synchronous command to that same connection, the
372 // thread on the far side might be busy processing the asynchronous
373 // command. So, we move to considering the second available thread
374 // for subsequent calls.
375 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000376 mSession->mClientConnectionsOffset =
377 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 }
379
380 // USE SERVING SOCKET (for nested transaction)
381 //
382 // asynchronous calls cannot be nested
383 if (use != ConnectionUse::CLIENT_ASYNC) {
384 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000385 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 0 /* index hint */);
387 }
388
389 // if our thread is already using a session, prioritize using that
390 if (exclusive != nullptr) {
391 mConnection = exclusive;
392 mReentrant = true;
393 break;
394 } else if (available != nullptr) {
395 mConnection = available;
396 mConnection->exclusiveTid = tid;
397 break;
398 }
399
400 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000401 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 "Not a client of any session. You must create a session to an "
403 "RPC server to make any non-nested (e.g. oneway or on another thread) "
404 "calls.");
405
406 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000407 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408 mSession->mAvailableConnectionCv.wait(_l);
409 }
410 mSession->mWaitingThreads--;
411}
412
413void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
414 sp<RpcConnection>* available,
415 std::vector<sp<RpcConnection>>& sockets,
416 size_t socketsIndexHint) {
417 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
418 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
419
420 if (*exclusive != nullptr) return; // consistent with break below
421
422 for (size_t i = 0; i < sockets.size(); i++) {
423 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
424
425 // take first available session (intuition = caching)
426 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
427 *available = socket;
428 continue;
429 }
430
431 // though, prefer to take session which is already inuse by this thread
432 // (nested transactions)
433 if (exclusive && socket->exclusiveTid == tid) {
434 *exclusive = socket;
435 break; // consistent with return above
436 }
437 }
438}
439
440RpcSession::ExclusiveConnection::~ExclusiveConnection() {
441 // reentrant use of a session means something less deep in the call stack
442 // is using this fd, and it retains the right to it. So, we don't give up
443 // exclusive ownership, and no thread is freed.
444 if (!mReentrant) {
445 std::unique_lock<std::mutex> _l(mSession->mMutex);
446 mConnection->exclusiveTid = std::nullopt;
447 if (mSession->mWaitingThreads > 0) {
448 _l.unlock();
449 mSession->mAvailableConnectionCv.notify_one();
450 }
451 }
452}
453
454} // namespace android