blob: f32aa7a72d188ee3ad4e34a7766eee3d2035c0f3 [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
116status_t RpcSession::readId() {
117 {
118 std::lock_guard<std::mutex> _l(mMutex);
119 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
120 }
121
122 int32_t id;
123
124 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
125 status_t status =
126 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
127 if (status != OK) return status;
128
129 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
130 mId = id;
131 return OK;
132}
133
Steven Morelanda63ff932021-05-12 00:03:15 +0000134void RpcSession::join(std::thread thread, unique_fd client) {
135 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000136
Steven Morelanda63ff932021-05-12 00:03:15 +0000137 {
138 std::lock_guard<std::mutex> _l(mMutex);
139 mThreads[thread.get_id()] = std::move(thread);
140 }
141
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000142 // must be registered to allow arbitrary client code executing commands to
143 // be able to do nested calls (we can't only read from it)
144 sp<RpcConnection> connection = assignServerToThisThread(std::move(client));
145
146 while (true) {
147 status_t error =
148 state()->getAndExecuteCommand(connection->fd, sp<RpcSession>::fromExisting(this));
149
150 if (error != OK) {
151 ALOGI("Binder connection thread closing w/ status %s", statusToString(error).c_str());
152 break;
153 }
154 }
155
156 LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
157 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000158
159 {
160 std::lock_guard<std::mutex> _l(mMutex);
161 auto it = mThreads.find(std::this_thread::get_id());
162 LOG_ALWAYS_FATAL_IF(it == mThreads.end());
163 it->second.detach();
164 mThreads.erase(it);
165 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000166}
167
Steven Morelandee78e762021-05-05 21:12:51 +0000168void RpcSession::terminateLocked() {
169 // TODO(b/185167543):
170 // - kindly notify other side of the connection of termination (can't be
171 // locked)
172 // - prevent new client/servers from being added
173 // - stop all threads which are currently reading/writing
174 // - terminate RpcState?
175
176 if (mTerminated) return;
177
178 sp<RpcServer> server = mForServer.promote();
179 if (server) {
180 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
181 }
182}
183
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184wp<RpcServer> RpcSession::server() {
185 return mForServer;
186}
187
188bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
189 {
190 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000191 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000193 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000194 }
195
196 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
197
198 // TODO(b/185167543): we should add additional sessions dynamically
199 // instead of all at once.
200 // TODO(b/186470974): first risk of blocking
201 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000202 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000203 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
204 statusToString(status).c_str());
205 return false;
206 }
207
208 if (status_t status = readId(); status != OK) {
209 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
210 statusToString(status).c_str());
211 return false;
212 }
213
214 // we've already setup one client
215 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000216 // TODO(b/185167543): shutdown existing connections?
217 if (!setupOneSocketClient(addr, mId.value())) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000218 }
219
220 return true;
221}
222
223bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000224 for (size_t tries = 0; tries < 5; tries++) {
225 if (tries > 0) usleep(10000);
226
227 unique_fd serverFd(
228 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
229 if (serverFd == -1) {
230 int savedErrno = errno;
231 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
232 strerror(savedErrno));
233 return false;
234 }
235
236 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
237 if (errno == ECONNRESET) {
238 ALOGW("Connection reset on %s", addr.toString().c_str());
239 continue;
240 }
241 int savedErrno = errno;
242 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
243 strerror(savedErrno));
244 return false;
245 }
246
247 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
248 int savedErrno = errno;
249 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
250 strerror(savedErrno));
251 return false;
252 }
253
254 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
255
Steven Morelandc8c256b2021-05-11 22:59:09 +0000256 addClientConnection(std::move(serverFd));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000257 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000258 }
259
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000260 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
261 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262}
263
Steven Morelandc8c256b2021-05-11 22:59:09 +0000264void RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265 std::lock_guard<std::mutex> _l(mMutex);
266 sp<RpcConnection> session = sp<RpcConnection>::make();
267 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000268 mClientConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000269}
270
271void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
272 mId = sessionId;
273 mForServer = server;
274}
275
276sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
277 std::lock_guard<std::mutex> _l(mMutex);
278 sp<RpcConnection> session = sp<RpcConnection>::make();
279 session->fd = std::move(fd);
280 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000281 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282
283 return session;
284}
285
286bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
287 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000288 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
289 it != mServerConnections.end()) {
290 mServerConnections.erase(it);
291 if (mServerConnections.size() == 0) {
Steven Morelandee78e762021-05-05 21:12:51 +0000292 terminateLocked();
293 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294 return true;
295 }
296 return false;
297}
298
299RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
300 ConnectionUse use)
301 : mSession(session) {
302 pid_t tid = gettid();
303 std::unique_lock<std::mutex> _l(mSession->mMutex);
304
305 mSession->mWaitingThreads++;
306 while (true) {
307 sp<RpcConnection> exclusive;
308 sp<RpcConnection> available;
309
310 // CHECK FOR DEDICATED CLIENT SOCKET
311 //
312 // A server/looper should always use a dedicated session if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000313 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
314 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315
316 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000317 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318 //
319 // Imagine we have more than one thread in play, and a single thread
320 // sends a synchronous, then an asynchronous command. Imagine the
321 // asynchronous command is sent on the first client connection. Then, if
322 // we naively send a synchronous command to that same connection, the
323 // thread on the far side might be busy processing the asynchronous
324 // command. So, we move to considering the second available thread
325 // for subsequent calls.
326 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000327 mSession->mClientConnectionsOffset =
328 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 }
330
331 // USE SERVING SOCKET (for nested transaction)
332 //
333 // asynchronous calls cannot be nested
334 if (use != ConnectionUse::CLIENT_ASYNC) {
335 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000336 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000337 0 /* index hint */);
338 }
339
340 // if our thread is already using a session, prioritize using that
341 if (exclusive != nullptr) {
342 mConnection = exclusive;
343 mReentrant = true;
344 break;
345 } else if (available != nullptr) {
346 mConnection = available;
347 mConnection->exclusiveTid = tid;
348 break;
349 }
350
351 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000352 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 "Not a client of any session. You must create a session to an "
354 "RPC server to make any non-nested (e.g. oneway or on another thread) "
355 "calls.");
356
357 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000358 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000359 mSession->mAvailableConnectionCv.wait(_l);
360 }
361 mSession->mWaitingThreads--;
362}
363
364void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
365 sp<RpcConnection>* available,
366 std::vector<sp<RpcConnection>>& sockets,
367 size_t socketsIndexHint) {
368 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
369 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
370
371 if (*exclusive != nullptr) return; // consistent with break below
372
373 for (size_t i = 0; i < sockets.size(); i++) {
374 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
375
376 // take first available session (intuition = caching)
377 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
378 *available = socket;
379 continue;
380 }
381
382 // though, prefer to take session which is already inuse by this thread
383 // (nested transactions)
384 if (exclusive && socket->exclusiveTid == tid) {
385 *exclusive = socket;
386 break; // consistent with return above
387 }
388 }
389}
390
391RpcSession::ExclusiveConnection::~ExclusiveConnection() {
392 // reentrant use of a session means something less deep in the call stack
393 // is using this fd, and it retains the right to it. So, we don't give up
394 // exclusive ownership, and no thread is freed.
395 if (!mReentrant) {
396 std::unique_lock<std::mutex> _l(mSession->mMutex);
397 mConnection->exclusiveTid = std::nullopt;
398 if (mSession->mWaitingThreads > 0) {
399 _l.unlock();
400 mSession->mAvailableConnectionCv.notify_one();
401 }
402 }
403}
404
405} // namespace android