blob: ea82f364002046bea4f094847d4aa1f396e2982a [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 Morelandbdb53ab2021-05-05 17:57:41 +0000147status_t RpcSession::readId() {
148 {
149 std::lock_guard<std::mutex> _l(mMutex);
150 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
151 }
152
153 int32_t id;
154
155 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
156 status_t status =
157 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
158 if (status != OK) return status;
159
160 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
161 mId = id;
162 return OK;
163}
164
Steven Moreland5802c2b2021-05-12 20:13:04 +0000165void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000166 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000167
Steven Morelanda63ff932021-05-12 00:03:15 +0000168 {
169 std::lock_guard<std::mutex> _l(mMutex);
170 mThreads[thread.get_id()] = std::move(thread);
171 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000172}
Steven Morelanda63ff932021-05-12 00:03:15 +0000173
Steven Moreland5802c2b2021-05-12 20:13:04 +0000174void RpcSession::join(unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000175 // must be registered to allow arbitrary client code executing commands to
176 // be able to do nested calls (we can't only read from it)
177 sp<RpcConnection> connection = assignServerToThisThread(std::move(client));
178
179 while (true) {
180 status_t error =
181 state()->getAndExecuteCommand(connection->fd, sp<RpcSession>::fromExisting(this));
182
183 if (error != OK) {
184 ALOGI("Binder connection thread closing w/ status %s", statusToString(error).c_str());
185 break;
186 }
187 }
188
189 LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
190 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000191
192 {
193 std::lock_guard<std::mutex> _l(mMutex);
194 auto it = mThreads.find(std::this_thread::get_id());
195 LOG_ALWAYS_FATAL_IF(it == mThreads.end());
196 it->second.detach();
197 mThreads.erase(it);
198 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199}
200
Steven Morelandee78e762021-05-05 21:12:51 +0000201void RpcSession::terminateLocked() {
202 // TODO(b/185167543):
203 // - kindly notify other side of the connection of termination (can't be
204 // locked)
205 // - prevent new client/servers from being added
206 // - stop all threads which are currently reading/writing
207 // - terminate RpcState?
208
209 if (mTerminated) return;
210
211 sp<RpcServer> server = mForServer.promote();
212 if (server) {
213 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
214 }
215}
216
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217wp<RpcServer> RpcSession::server() {
218 return mForServer;
219}
220
221bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
222 {
223 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000224 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000226 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000227 }
228
229 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
230
231 // TODO(b/185167543): we should add additional sessions dynamically
232 // instead of all at once.
233 // TODO(b/186470974): first risk of blocking
234 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000235 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
237 statusToString(status).c_str());
238 return false;
239 }
240
241 if (status_t status = readId(); status != OK) {
242 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
243 statusToString(status).c_str());
244 return false;
245 }
246
247 // we've already setup one client
248 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000249 // TODO(b/185167543): shutdown existing connections?
250 if (!setupOneSocketClient(addr, mId.value())) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251 }
252
253 return true;
254}
255
256bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000257 for (size_t tries = 0; tries < 5; tries++) {
258 if (tries > 0) usleep(10000);
259
260 unique_fd serverFd(
261 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
262 if (serverFd == -1) {
263 int savedErrno = errno;
264 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
265 strerror(savedErrno));
266 return false;
267 }
268
269 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
270 if (errno == ECONNRESET) {
271 ALOGW("Connection reset on %s", addr.toString().c_str());
272 continue;
273 }
274 int savedErrno = errno;
275 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
276 strerror(savedErrno));
277 return false;
278 }
279
280 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
281 int savedErrno = errno;
282 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
283 strerror(savedErrno));
284 return false;
285 }
286
287 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
288
Steven Morelandc8c256b2021-05-11 22:59:09 +0000289 addClientConnection(std::move(serverFd));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000290 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 }
292
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000293 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
294 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295}
296
Steven Morelandc8c256b2021-05-11 22:59:09 +0000297void RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298 std::lock_guard<std::mutex> _l(mMutex);
299 sp<RpcConnection> session = sp<RpcConnection>::make();
300 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000301 mClientConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302}
303
304void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
305 mId = sessionId;
306 mForServer = server;
307}
308
309sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
310 std::lock_guard<std::mutex> _l(mMutex);
311 sp<RpcConnection> session = sp<RpcConnection>::make();
312 session->fd = std::move(fd);
313 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000314 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315
316 return session;
317}
318
319bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
320 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000321 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
322 it != mServerConnections.end()) {
323 mServerConnections.erase(it);
324 if (mServerConnections.size() == 0) {
Steven Morelandee78e762021-05-05 21:12:51 +0000325 terminateLocked();
326 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000327 return true;
328 }
329 return false;
330}
331
332RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
333 ConnectionUse use)
334 : mSession(session) {
335 pid_t tid = gettid();
336 std::unique_lock<std::mutex> _l(mSession->mMutex);
337
338 mSession->mWaitingThreads++;
339 while (true) {
340 sp<RpcConnection> exclusive;
341 sp<RpcConnection> available;
342
343 // CHECK FOR DEDICATED CLIENT SOCKET
344 //
345 // A server/looper should always use a dedicated session if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000346 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
347 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348
349 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000350 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 //
352 // Imagine we have more than one thread in play, and a single thread
353 // sends a synchronous, then an asynchronous command. Imagine the
354 // asynchronous command is sent on the first client connection. Then, if
355 // we naively send a synchronous command to that same connection, the
356 // thread on the far side might be busy processing the asynchronous
357 // command. So, we move to considering the second available thread
358 // for subsequent calls.
359 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000360 mSession->mClientConnectionsOffset =
361 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 }
363
364 // USE SERVING SOCKET (for nested transaction)
365 //
366 // asynchronous calls cannot be nested
367 if (use != ConnectionUse::CLIENT_ASYNC) {
368 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000369 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000370 0 /* index hint */);
371 }
372
373 // if our thread is already using a session, prioritize using that
374 if (exclusive != nullptr) {
375 mConnection = exclusive;
376 mReentrant = true;
377 break;
378 } else if (available != nullptr) {
379 mConnection = available;
380 mConnection->exclusiveTid = tid;
381 break;
382 }
383
384 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000385 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 "Not a client of any session. You must create a session to an "
387 "RPC server to make any non-nested (e.g. oneway or on another thread) "
388 "calls.");
389
390 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000391 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 mSession->mAvailableConnectionCv.wait(_l);
393 }
394 mSession->mWaitingThreads--;
395}
396
397void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
398 sp<RpcConnection>* available,
399 std::vector<sp<RpcConnection>>& sockets,
400 size_t socketsIndexHint) {
401 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
402 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
403
404 if (*exclusive != nullptr) return; // consistent with break below
405
406 for (size_t i = 0; i < sockets.size(); i++) {
407 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
408
409 // take first available session (intuition = caching)
410 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
411 *available = socket;
412 continue;
413 }
414
415 // though, prefer to take session which is already inuse by this thread
416 // (nested transactions)
417 if (exclusive && socket->exclusiveTid == tid) {
418 *exclusive = socket;
419 break; // consistent with return above
420 }
421 }
422}
423
424RpcSession::ExclusiveConnection::~ExclusiveConnection() {
425 // reentrant use of a session means something less deep in the call stack
426 // is using this fd, and it retains the right to it. So, we don't give up
427 // exclusive ownership, and no thread is freed.
428 if (!mReentrant) {
429 std::unique_lock<std::mutex> _l(mSession->mMutex);
430 mConnection->exclusiveTid = std::nullopt;
431 if (mSession->mWaitingThreads > 0) {
432 _l.unlock();
433 mSession->mAvailableConnectionCv.notify_one();
434 }
435 }
436}
437
438} // namespace android