blob: bf998c1cd8129796b9b3b36289909ad2c6558d4a [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);
52 LOG_ALWAYS_FATAL_IF(mServers.size() != 0,
53 "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
64#ifdef __BIONIC__
65
66bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
67 return setupSocketClient(VsockSocketAddress(cid, port));
68}
69
70#endif // __BIONIC__
71
72bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
73 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
74 if (aiStart == nullptr) return false;
75 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
76 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
77 if (setupSocketClient(socketAddress)) return true;
78 }
79 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
80 return false;
81}
82
83bool RpcSession::addNullDebuggingClient() {
84 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
85
86 if (serverFd == -1) {
87 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
88 return false;
89 }
90
91 addClient(std::move(serverFd));
92 return true;
93}
94
95sp<IBinder> RpcSession::getRootObject() {
96 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
97 return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
98}
99
100status_t RpcSession::getMaxThreads(size_t* maxThreads) {
101 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
102 return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
103}
104
105status_t RpcSession::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
106 Parcel* reply, uint32_t flags) {
107 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
108 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
109 : ConnectionUse::CLIENT);
110 return state()->transact(connection.fd(), address, code, data,
111 sp<RpcSession>::fromExisting(this), reply, flags);
112}
113
114status_t RpcSession::sendDecStrong(const RpcAddress& address) {
115 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
116 ConnectionUse::CLIENT_REFCOUNT);
117 return state()->sendDecStrong(connection.fd(), address);
118}
119
120status_t RpcSession::readId() {
121 {
122 std::lock_guard<std::mutex> _l(mMutex);
123 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
124 }
125
126 int32_t id;
127
128 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
129 status_t status =
130 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
131 if (status != OK) return status;
132
133 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
134 mId = id;
135 return OK;
136}
137
138void RpcSession::startThread(unique_fd client) {
139 std::lock_guard<std::mutex> _l(mMutex);
140 sp<RpcSession> holdThis = sp<RpcSession>::fromExisting(this);
141 int fd = client.release();
142 auto thread = std::thread([=] {
143 holdThis->join(unique_fd(fd));
144 {
145 std::lock_guard<std::mutex> _l(holdThis->mMutex);
146 size_t erased = mThreads.erase(std::this_thread::get_id());
147 LOG_ALWAYS_FATAL_IF(erased != 0, "Could not erase thread.");
148 }
149 });
150 mThreads[thread.get_id()] = std::move(thread);
151}
152
153void RpcSession::join(unique_fd client) {
154 // 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");
170}
171
Steven Morelandee78e762021-05-05 21:12:51 +0000172void RpcSession::terminateLocked() {
173 // TODO(b/185167543):
174 // - kindly notify other side of the connection of termination (can't be
175 // locked)
176 // - prevent new client/servers from being added
177 // - stop all threads which are currently reading/writing
178 // - terminate RpcState?
179
180 if (mTerminated) return;
181
182 sp<RpcServer> server = mForServer.promote();
183 if (server) {
184 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
185 }
186}
187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188wp<RpcServer> RpcSession::server() {
189 return mForServer;
190}
191
192bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
193 {
194 std::lock_guard<std::mutex> _l(mMutex);
195 LOG_ALWAYS_FATAL_IF(mClients.size() != 0,
196 "Must only setup session once, but already has %zu clients",
197 mClients.size());
198 }
199
200 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
201
202 // TODO(b/185167543): we should add additional sessions dynamically
203 // instead of all at once.
204 // TODO(b/186470974): first risk of blocking
205 size_t numThreadsAvailable;
206 if (status_t status = getMaxThreads(&numThreadsAvailable); status != OK) {
207 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
208 statusToString(status).c_str());
209 return false;
210 }
211
212 if (status_t status = readId(); status != OK) {
213 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
214 statusToString(status).c_str());
215 return false;
216 }
217
218 // we've already setup one client
219 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
220 // TODO(b/185167543): avoid race w/ accept4 not being called on server
221 for (size_t tries = 0; tries < 5; tries++) {
222 if (setupOneSocketClient(addr, mId.value())) break;
223 usleep(10000);
224 }
225 }
226
227 return true;
228}
229
230bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
231 unique_fd serverFd(
232 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
233 if (serverFd == -1) {
234 int savedErrno = errno;
235 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
236 return false;
237 }
238
239 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
240 int savedErrno = errno;
241 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
242 return false;
243 }
244
245 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
246 int savedErrno = errno;
247 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
248 strerror(savedErrno));
249 return false;
250 }
251
252 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
253
254 addClient(std::move(serverFd));
255 return true;
256}
257
258void RpcSession::addClient(unique_fd fd) {
259 std::lock_guard<std::mutex> _l(mMutex);
260 sp<RpcConnection> session = sp<RpcConnection>::make();
261 session->fd = std::move(fd);
262 mClients.push_back(session);
263}
264
265void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
266 mId = sessionId;
267 mForServer = server;
268}
269
270sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
271 std::lock_guard<std::mutex> _l(mMutex);
272 sp<RpcConnection> session = sp<RpcConnection>::make();
273 session->fd = std::move(fd);
274 session->exclusiveTid = gettid();
275 mServers.push_back(session);
276
277 return session;
278}
279
280bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
281 std::lock_guard<std::mutex> _l(mMutex);
282 if (auto it = std::find(mServers.begin(), mServers.end(), connection); it != mServers.end()) {
283 mServers.erase(it);
Steven Morelandee78e762021-05-05 21:12:51 +0000284 if (mServers.size() == 0) {
285 terminateLocked();
286 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 return true;
288 }
289 return false;
290}
291
292RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
293 ConnectionUse use)
294 : mSession(session) {
295 pid_t tid = gettid();
296 std::unique_lock<std::mutex> _l(mSession->mMutex);
297
298 mSession->mWaitingThreads++;
299 while (true) {
300 sp<RpcConnection> exclusive;
301 sp<RpcConnection> available;
302
303 // CHECK FOR DEDICATED CLIENT SOCKET
304 //
305 // A server/looper should always use a dedicated session if available
306 findConnection(tid, &exclusive, &available, mSession->mClients, mSession->mClientsOffset);
307
308 // WARNING: this assumes a server cannot request its client to send
309 // a transaction, as mServers is excluded below.
310 //
311 // Imagine we have more than one thread in play, and a single thread
312 // sends a synchronous, then an asynchronous command. Imagine the
313 // asynchronous command is sent on the first client connection. Then, if
314 // we naively send a synchronous command to that same connection, the
315 // thread on the far side might be busy processing the asynchronous
316 // command. So, we move to considering the second available thread
317 // for subsequent calls.
318 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
319 mSession->mClientsOffset = (mSession->mClientsOffset + 1) % mSession->mClients.size();
320 }
321
322 // USE SERVING SOCKET (for nested transaction)
323 //
324 // asynchronous calls cannot be nested
325 if (use != ConnectionUse::CLIENT_ASYNC) {
326 // server connections are always assigned to a thread
327 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServers,
328 0 /* index hint */);
329 }
330
331 // if our thread is already using a session, prioritize using that
332 if (exclusive != nullptr) {
333 mConnection = exclusive;
334 mReentrant = true;
335 break;
336 } else if (available != nullptr) {
337 mConnection = available;
338 mConnection->exclusiveTid = tid;
339 break;
340 }
341
342 // in regular binder, this would usually be a deadlock :)
343 LOG_ALWAYS_FATAL_IF(mSession->mClients.size() == 0,
344 "Not a client of any session. You must create a session to an "
345 "RPC server to make any non-nested (e.g. oneway or on another thread) "
346 "calls.");
347
348 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
349 mSession->mClients.size(), mSession->mServers.size());
350 mSession->mAvailableConnectionCv.wait(_l);
351 }
352 mSession->mWaitingThreads--;
353}
354
355void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
356 sp<RpcConnection>* available,
357 std::vector<sp<RpcConnection>>& sockets,
358 size_t socketsIndexHint) {
359 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
360 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
361
362 if (*exclusive != nullptr) return; // consistent with break below
363
364 for (size_t i = 0; i < sockets.size(); i++) {
365 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
366
367 // take first available session (intuition = caching)
368 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
369 *available = socket;
370 continue;
371 }
372
373 // though, prefer to take session which is already inuse by this thread
374 // (nested transactions)
375 if (exclusive && socket->exclusiveTid == tid) {
376 *exclusive = socket;
377 break; // consistent with return above
378 }
379 }
380}
381
382RpcSession::ExclusiveConnection::~ExclusiveConnection() {
383 // reentrant use of a session means something less deep in the call stack
384 // is using this fd, and it retains the right to it. So, we don't give up
385 // exclusive ownership, and no thread is freed.
386 if (!mReentrant) {
387 std::unique_lock<std::mutex> _l(mSession->mMutex);
388 mConnection->exclusiveTid = std::nullopt;
389 if (mSession->mWaitingThreads > 0) {
390 _l.unlock();
391 mSession->mAvailableConnectionCv.notify_one();
392 }
393 }
394}
395
396} // namespace android