blob: cb6c787d19caa5d8849ea36a52c8010345d29e03 [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
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
87 addClient(std::move(serverFd));
88 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
96status_t RpcSession::getMaxThreads(size_t* maxThreads) {
97 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
134void RpcSession::startThread(unique_fd client) {
135 std::lock_guard<std::mutex> _l(mMutex);
136 sp<RpcSession> holdThis = sp<RpcSession>::fromExisting(this);
137 int fd = client.release();
138 auto thread = std::thread([=] {
139 holdThis->join(unique_fd(fd));
140 {
141 std::lock_guard<std::mutex> _l(holdThis->mMutex);
Steven Moreland2ff0d472021-05-05 22:20:40 +0000142 auto it = mThreads.find(std::this_thread::get_id());
143 LOG_ALWAYS_FATAL_IF(it == mThreads.end());
144 it->second.detach();
145 mThreads.erase(it);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000146 }
147 });
148 mThreads[thread.get_id()] = std::move(thread);
149}
150
151void RpcSession::join(unique_fd client) {
152 // must be registered to allow arbitrary client code executing commands to
153 // be able to do nested calls (we can't only read from it)
154 sp<RpcConnection> connection = assignServerToThisThread(std::move(client));
155
156 while (true) {
157 status_t error =
158 state()->getAndExecuteCommand(connection->fd, sp<RpcSession>::fromExisting(this));
159
160 if (error != OK) {
161 ALOGI("Binder connection thread closing w/ status %s", statusToString(error).c_str());
162 break;
163 }
164 }
165
166 LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
167 "bad state: connection object guaranteed to be in list");
168}
169
Steven Morelandee78e762021-05-05 21:12:51 +0000170void RpcSession::terminateLocked() {
171 // TODO(b/185167543):
172 // - kindly notify other side of the connection of termination (can't be
173 // locked)
174 // - prevent new client/servers from being added
175 // - stop all threads which are currently reading/writing
176 // - terminate RpcState?
177
178 if (mTerminated) return;
179
180 sp<RpcServer> server = mForServer.promote();
181 if (server) {
182 server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
183 }
184}
185
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186wp<RpcServer> RpcSession::server() {
187 return mForServer;
188}
189
190bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
191 {
192 std::lock_guard<std::mutex> _l(mMutex);
193 LOG_ALWAYS_FATAL_IF(mClients.size() != 0,
194 "Must only setup session once, but already has %zu clients",
195 mClients.size());
196 }
197
198 if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
199
200 // TODO(b/185167543): we should add additional sessions dynamically
201 // instead of all at once.
202 // TODO(b/186470974): first risk of blocking
203 size_t numThreadsAvailable;
204 if (status_t status = getMaxThreads(&numThreadsAvailable); status != OK) {
205 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
206 statusToString(status).c_str());
207 return false;
208 }
209
210 if (status_t status = readId(); status != OK) {
211 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
212 statusToString(status).c_str());
213 return false;
214 }
215
216 // we've already setup one client
217 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000218 // TODO(b/185167543): shutdown existing connections?
219 if (!setupOneSocketClient(addr, mId.value())) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000220 }
221
222 return true;
223}
224
225bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000226 for (size_t tries = 0; tries < 5; tries++) {
227 if (tries > 0) usleep(10000);
228
229 unique_fd serverFd(
230 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
231 if (serverFd == -1) {
232 int savedErrno = errno;
233 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
234 strerror(savedErrno));
235 return false;
236 }
237
238 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
239 if (errno == ECONNRESET) {
240 ALOGW("Connection reset on %s", addr.toString().c_str());
241 continue;
242 }
243 int savedErrno = errno;
244 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
245 strerror(savedErrno));
246 return false;
247 }
248
249 if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
250 int savedErrno = errno;
251 ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
252 strerror(savedErrno));
253 return false;
254 }
255
256 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
257
258 addClient(std::move(serverFd));
259 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 }
261
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000262 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
263 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000264}
265
266void RpcSession::addClient(unique_fd fd) {
267 std::lock_guard<std::mutex> _l(mMutex);
268 sp<RpcConnection> session = sp<RpcConnection>::make();
269 session->fd = std::move(fd);
270 mClients.push_back(session);
271}
272
273void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
274 mId = sessionId;
275 mForServer = server;
276}
277
278sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
279 std::lock_guard<std::mutex> _l(mMutex);
280 sp<RpcConnection> session = sp<RpcConnection>::make();
281 session->fd = std::move(fd);
282 session->exclusiveTid = gettid();
283 mServers.push_back(session);
284
285 return session;
286}
287
288bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
289 std::lock_guard<std::mutex> _l(mMutex);
290 if (auto it = std::find(mServers.begin(), mServers.end(), connection); it != mServers.end()) {
291 mServers.erase(it);
Steven Morelandee78e762021-05-05 21:12:51 +0000292 if (mServers.size() == 0) {
293 terminateLocked();
294 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295 return true;
296 }
297 return false;
298}
299
300RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
301 ConnectionUse use)
302 : mSession(session) {
303 pid_t tid = gettid();
304 std::unique_lock<std::mutex> _l(mSession->mMutex);
305
306 mSession->mWaitingThreads++;
307 while (true) {
308 sp<RpcConnection> exclusive;
309 sp<RpcConnection> available;
310
311 // CHECK FOR DEDICATED CLIENT SOCKET
312 //
313 // A server/looper should always use a dedicated session if available
314 findConnection(tid, &exclusive, &available, mSession->mClients, mSession->mClientsOffset);
315
316 // WARNING: this assumes a server cannot request its client to send
317 // a transaction, as mServers is excluded below.
318 //
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)) {
327 mSession->mClientsOffset = (mSession->mClientsOffset + 1) % mSession->mClients.size();
328 }
329
330 // USE SERVING SOCKET (for nested transaction)
331 //
332 // asynchronous calls cannot be nested
333 if (use != ConnectionUse::CLIENT_ASYNC) {
334 // server connections are always assigned to a thread
335 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServers,
336 0 /* index hint */);
337 }
338
339 // if our thread is already using a session, prioritize using that
340 if (exclusive != nullptr) {
341 mConnection = exclusive;
342 mReentrant = true;
343 break;
344 } else if (available != nullptr) {
345 mConnection = available;
346 mConnection->exclusiveTid = tid;
347 break;
348 }
349
350 // in regular binder, this would usually be a deadlock :)
351 LOG_ALWAYS_FATAL_IF(mSession->mClients.size() == 0,
352 "Not a client of any session. You must create a session to an "
353 "RPC server to make any non-nested (e.g. oneway or on another thread) "
354 "calls.");
355
356 LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
357 mSession->mClients.size(), mSession->mServers.size());
358 mSession->mAvailableConnectionCv.wait(_l);
359 }
360 mSession->mWaitingThreads--;
361}
362
363void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
364 sp<RpcConnection>* available,
365 std::vector<sp<RpcConnection>>& sockets,
366 size_t socketsIndexHint) {
367 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
368 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
369
370 if (*exclusive != nullptr) return; // consistent with break below
371
372 for (size_t i = 0; i < sockets.size(); i++) {
373 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
374
375 // take first available session (intuition = caching)
376 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
377 *available = socket;
378 continue;
379 }
380
381 // though, prefer to take session which is already inuse by this thread
382 // (nested transactions)
383 if (exclusive && socket->exclusiveTid == tid) {
384 *exclusive = socket;
385 break; // consistent with return above
386 }
387 }
388}
389
390RpcSession::ExclusiveConnection::~ExclusiveConnection() {
391 // reentrant use of a session means something less deep in the call stack
392 // is using this fd, and it retains the right to it. So, we don't give up
393 // exclusive ownership, and no thread is freed.
394 if (!mReentrant) {
395 std::unique_lock<std::mutex> _l(mSession->mMutex);
396 mConnection->exclusiveTid = std::nullopt;
397 if (mSession->mWaitingThreads > 0) {
398 _l.unlock();
399 mSession->mAvailableConnectionCv.notify_one();
400 }
401 }
402}
403
404} // namespace android