blob: 4efa6bb1a93c24b444f2a931b84be23ee87445dd [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>
22#include <unistd.h>
23
24#include <string_view>
25
26#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000027#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000028#include <binder/Stability.h>
29#include <utils/String8.h>
30
31#include "RpcSocketAddress.h"
32#include "RpcState.h"
33#include "RpcWireFormat.h"
34
35#ifdef __GLIBC__
36extern "C" pid_t gettid();
37#endif
38
39namespace android {
40
41using base::unique_fd;
42
43RpcSession::RpcSession() {
44 LOG_RPC_DETAIL("RpcSession created %p", this);
45
46 mState = std::make_unique<RpcState>();
47}
48RpcSession::~RpcSession() {
49 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
50
51 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +000052 LOG_ALWAYS_FATAL_IF(mServerConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000053 "Should not be able to destroy a session with servers in use.");
54}
55
56sp<RpcSession> RpcSession::make() {
57 return sp<RpcSession>::make();
58}
59
60bool RpcSession::setupUnixDomainClient(const char* path) {
61 return setupSocketClient(UnixSocketAddress(path));
62}
63
Steven Morelandbdb53ab2021-05-05 17:57:41 +000064bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
65 return setupSocketClient(VsockSocketAddress(cid, port));
66}
67
Steven Morelandbdb53ab2021-05-05 17:57:41 +000068bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
69 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
70 if (aiStart == nullptr) return false;
71 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
72 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
73 if (setupSocketClient(socketAddress)) return true;
74 }
75 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
76 return false;
77}
78
79bool RpcSession::addNullDebuggingClient() {
80 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
81
82 if (serverFd == -1) {
83 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
84 return false;
85 }
86
Steven Morelandc8c256b2021-05-11 22:59:09 +000087 addClientConnection(std::move(serverFd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000088 return true;
89}
90
91sp<IBinder> RpcSession::getRootObject() {
92 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
93 return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
94}
95
Steven Moreland1be91352021-05-11 22:12:15 +000096status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000097 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
98 return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
99}
100
101status_t RpcSession::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
102 Parcel* reply, uint32_t flags) {
103 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
104 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
105 : ConnectionUse::CLIENT);
106 return state()->transact(connection.fd(), address, code, data,
107 sp<RpcSession>::fromExisting(this), reply, flags);
108}
109
110status_t RpcSession::sendDecStrong(const RpcAddress& address) {
111 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
112 ConnectionUse::CLIENT_REFCOUNT);
113 return state()->sendDecStrong(connection.fd(), address);
114}
115
Steven Morelande47511f2021-05-20 00:07:41 +0000116std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
117 auto ret = std::make_unique<RpcSession::FdTrigger>();
118 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) return nullptr;
119 return ret;
120}
121
122void RpcSession::FdTrigger::trigger() {
123 mWrite.reset();
124}
125
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000126status_t RpcSession::readId() {
127 {
128 std::lock_guard<std::mutex> _l(mMutex);
129 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
130 }
131
132 int32_t id;
133
134 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
135 status_t status =
136 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
137 if (status != OK) return status;
138
139 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
140 mId = id;
141 return OK;
142}
143
Steven Moreland5802c2b2021-05-12 20:13:04 +0000144void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000145 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000146
Steven Morelanda63ff932021-05-12 00:03:15 +0000147 {
148 std::lock_guard<std::mutex> _l(mMutex);
149 mThreads[thread.get_id()] = std::move(thread);
150 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000151}
Steven Morelanda63ff932021-05-12 00:03:15 +0000152
Steven Moreland5802c2b2021-05-12 20:13:04 +0000153void RpcSession::join(unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 // must be registered to allow arbitrary client code executing commands to
155 // be able to do nested calls (we can't only read from it)
156 sp<RpcConnection> connection = assignServerToThisThread(std::move(client));
157
158 while (true) {
159 status_t error =
160 state()->getAndExecuteCommand(connection->fd, sp<RpcSession>::fromExisting(this));
161
162 if (error != OK) {
163 ALOGI("Binder connection thread closing w/ status %s", statusToString(error).c_str());
164 break;
165 }
166 }
167
168 LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
169 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000170
171 {
172 std::lock_guard<std::mutex> _l(mMutex);
173 auto it = mThreads.find(std::this_thread::get_id());
174 LOG_ALWAYS_FATAL_IF(it == mThreads.end());
175 it->second.detach();
176 mThreads.erase(it);
177 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178}
179
Steven Morelandee78e762021-05-05 21:12:51 +0000180void RpcSession::terminateLocked() {
181 // TODO(b/185167543):
182 // - kindly notify other side of the connection of termination (can't be
183 // locked)
184 // - prevent new client/servers from being added
185 // - stop all threads which are currently reading/writing
186 // - terminate RpcState?
187
188 if (mTerminated) return;
189
190 sp<RpcServer> server = mForServer.promote();
191 if (server) {
192 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
193 }
194}
195
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196wp<RpcServer> RpcSession::server() {
197 return mForServer;
198}
199
200bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
201 {
202 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000203 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000205 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000206 }
207
208 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
209
210 // TODO(b/185167543): we should add additional sessions dynamically
211 // instead of all at once.
212 // TODO(b/186470974): first risk of blocking
213 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000214 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
216 statusToString(status).c_str());
217 return false;
218 }
219
220 if (status_t status = readId(); status != OK) {
221 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
222 statusToString(status).c_str());
223 return false;
224 }
225
226 // we've already setup one client
227 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000228 // TODO(b/185167543): shutdown existing connections?
229 if (!setupOneSocketClient(addr, mId.value())) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000230 }
231
232 return true;
233}
234
235bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000236 for (size_t tries = 0; tries < 5; tries++) {
237 if (tries > 0) usleep(10000);
238
239 unique_fd serverFd(
240 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
241 if (serverFd == -1) {
242 int savedErrno = errno;
243 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
244 strerror(savedErrno));
245 return false;
246 }
247
248 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
249 if (errno == ECONNRESET) {
250 ALOGW("Connection reset on %s", addr.toString().c_str());
251 continue;
252 }
253 int savedErrno = errno;
254 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
255 strerror(savedErrno));
256 return false;
257 }
258
259 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
260 int savedErrno = errno;
261 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
262 strerror(savedErrno));
263 return false;
264 }
265
266 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
267
Steven Morelandc8c256b2021-05-11 22:59:09 +0000268 addClientConnection(std::move(serverFd));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000269 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270 }
271
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000272 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
273 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274}
275
Steven Morelandc8c256b2021-05-11 22:59:09 +0000276void RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000277 std::lock_guard<std::mutex> _l(mMutex);
278 sp<RpcConnection> session = sp<RpcConnection>::make();
279 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000280 mClientConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281}
282
283void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
284 mId = sessionId;
285 mForServer = server;
286}
287
288sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
289 std::lock_guard<std::mutex> _l(mMutex);
290 sp<RpcConnection> session = sp<RpcConnection>::make();
291 session->fd = std::move(fd);
292 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000293 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294
295 return session;
296}
297
298bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
299 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000300 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
301 it != mServerConnections.end()) {
302 mServerConnections.erase(it);
303 if (mServerConnections.size() == 0) {
Steven Morelandee78e762021-05-05 21:12:51 +0000304 terminateLocked();
305 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 return true;
307 }
308 return false;
309}
310
311RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
312 ConnectionUse use)
313 : mSession(session) {
314 pid_t tid = gettid();
315 std::unique_lock<std::mutex> _l(mSession->mMutex);
316
317 mSession->mWaitingThreads++;
318 while (true) {
319 sp<RpcConnection> exclusive;
320 sp<RpcConnection> available;
321
322 // CHECK FOR DEDICATED CLIENT SOCKET
323 //
324 // A server/looper should always use a dedicated session if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000325 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
326 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000327
328 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000329 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000330 //
331 // Imagine we have more than one thread in play, and a single thread
332 // sends a synchronous, then an asynchronous command. Imagine the
333 // asynchronous command is sent on the first client connection. Then, if
334 // we naively send a synchronous command to that same connection, the
335 // thread on the far side might be busy processing the asynchronous
336 // command. So, we move to considering the second available thread
337 // for subsequent calls.
338 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000339 mSession->mClientConnectionsOffset =
340 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000341 }
342
343 // USE SERVING SOCKET (for nested transaction)
344 //
345 // asynchronous calls cannot be nested
346 if (use != ConnectionUse::CLIENT_ASYNC) {
347 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000348 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000349 0 /* index hint */);
350 }
351
352 // if our thread is already using a session, prioritize using that
353 if (exclusive != nullptr) {
354 mConnection = exclusive;
355 mReentrant = true;
356 break;
357 } else if (available != nullptr) {
358 mConnection = available;
359 mConnection->exclusiveTid = tid;
360 break;
361 }
362
363 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000364 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000365 "Not a client of any session. You must create a session to an "
366 "RPC server to make any non-nested (e.g. oneway or on another thread) "
367 "calls.");
368
369 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000370 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000371 mSession->mAvailableConnectionCv.wait(_l);
372 }
373 mSession->mWaitingThreads--;
374}
375
376void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
377 sp<RpcConnection>* available,
378 std::vector<sp<RpcConnection>>& sockets,
379 size_t socketsIndexHint) {
380 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
381 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
382
383 if (*exclusive != nullptr) return; // consistent with break below
384
385 for (size_t i = 0; i < sockets.size(); i++) {
386 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
387
388 // take first available session (intuition = caching)
389 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
390 *available = socket;
391 continue;
392 }
393
394 // though, prefer to take session which is already inuse by this thread
395 // (nested transactions)
396 if (exclusive && socket->exclusiveTid == tid) {
397 *exclusive = socket;
398 break; // consistent with return above
399 }
400 }
401}
402
403RpcSession::ExclusiveConnection::~ExclusiveConnection() {
404 // reentrant use of a session means something less deep in the call stack
405 // is using this fd, and it retains the right to it. So, we don't give up
406 // exclusive ownership, and no thread is freed.
407 if (!mReentrant) {
408 std::unique_lock<std::mutex> _l(mSession->mMutex);
409 mConnection->exclusiveTid = std::nullopt;
410 if (mSession->mWaitingThreads > 0) {
411 _l.unlock();
412 mSession->mAvailableConnectionCv.notify_one();
413 }
414 }
415}
416
417} // namespace android