blob: 4edc2029dcba9938a026ab53fff30bad668bd6f9 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +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 "RpcServer"
18
Steven Morelandc5032042021-09-30 15:40:27 -070019#include <inttypes.h>
Steven Moreland798e0d12021-07-14 23:19:25 +000020#include <poll.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000021#include <sys/socket.h>
22#include <sys/un.h>
23
Steven Morelandf137de92021-04-24 01:54:26 +000024#include <thread>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <vector>
26
Steven Moreland826367f2021-09-10 14:05:31 -070027#include <android-base/file.h>
28#include <android-base/hex.h>
Steven Moreland5802c2b2021-05-12 20:13:04 +000029#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/Parcel.h>
31#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070032#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <log/log.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034
Yifan Hong8c950422021-08-05 17:13:55 -070035#include "FdTrigger.h"
Steven Moreland611d15f2021-05-01 01:28:27 +000036#include "RpcSocketAddress.h"
Yifan Hong1a235852021-05-13 16:07:47 -070037#include "RpcState.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038#include "RpcWireFormat.h"
39
40namespace android {
41
Steven Morelandc5032042021-09-30 15:40:27 -070042constexpr size_t kSessionIdBytes = 32;
43
Steven Moreland5802c2b2021-05-12 20:13:04 +000044using base::ScopeGuard;
Steven Moreland611d15f2021-05-01 01:28:27 +000045using base::unique_fd;
46
Yifan Hongecf937d2021-08-11 17:29:28 -070047RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
Yifan Hong436f0e62021-05-19 15:25:34 -070048RpcServer::~RpcServer() {
49 (void)shutdown();
50}
Steven Moreland5553ac42020-11-11 02:14:45 +000051
Yifan Hong702115c2021-06-24 15:39:18 -070052sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
53 // Default is without TLS.
54 if (rpcTransportCtxFactory == nullptr)
55 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
Yifan Hongecf937d2021-08-11 17:29:28 -070056 auto ctx = rpcTransportCtxFactory->newServerCtx();
57 if (ctx == nullptr) return nullptr;
58 return sp<RpcServer>::make(std::move(ctx));
Steven Moreland5553ac42020-11-11 02:14:45 +000059}
60
61void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
62 mAgreedExperimental = true;
63}
64
Steven Moreland2372f9d2021-08-05 15:42:01 -070065status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000066 return setupSocketServer(UnixSocketAddress(path));
67}
68
Steven Moreland2372f9d2021-08-05 15:42:01 -070069status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000070 // realizing value w/ this type at compile time to avoid ubsan abort
71 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
72
73 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
74}
75
Steven Moreland2372f9d2021-08-05 15:42:01 -070076status_t RpcServer::setupInetServer(const char* address, unsigned int port,
77 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000078 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000079 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070080 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000081 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000082 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070083 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000084 continue;
85 }
86
87 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
88 sockaddr_in addr{};
89 socklen_t len = sizeof(addr);
90 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
91 int savedErrno = errno;
92 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
93 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070094 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000095 }
96 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
97 static_cast<size_t>(len), sizeof(addr));
98 unsigned int realPort = ntohs(addr.sin_port);
99 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
100 "Requesting inet server on %s but it is set up on %u.",
101 socketAddress.toString().c_str(), realPort);
102
103 if (assignedPort != nullptr) {
104 *assignedPort = realPort;
105 }
106
Steven Moreland2372f9d2021-08-05 15:42:01 -0700107 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000108 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000109 ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", address,
Steven Moreland611d15f2021-05-01 01:28:27 +0000110 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700111 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000112}
113
Steven Morelandf137de92021-04-24 01:54:26 +0000114void RpcServer::setMaxThreads(size_t threads) {
115 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700116 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000117 mMaxThreads = threads;
118}
119
120size_t RpcServer::getMaxThreads() {
121 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000122}
123
Steven Morelandbf57bce2021-07-26 15:26:12 -0700124void RpcServer::setProtocolVersion(uint32_t version) {
125 mProtocolVersion = version;
126}
127
Steven Moreland5553ac42020-11-11 02:14:45 +0000128void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000129 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700130 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700131 mRootObjectWeak = mRootObject = binder;
132}
133
134void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
135 std::lock_guard<std::mutex> _l(mLock);
136 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700137 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700138 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000139}
Steven Moreland51c44a92021-10-14 16:50:35 -0700140void RpcServer::setPerSessionRootObject(
141 std::function<sp<IBinder>(const sockaddr*, socklen_t)>&& makeObject) {
142 std::lock_guard<std::mutex> _l(mLock);
143 mRootObject.clear();
144 mRootObjectWeak.clear();
145 mRootObjectFactory = std::move(makeObject);
146}
Steven Moreland5553ac42020-11-11 02:14:45 +0000147
148sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000149 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700150 bool hasWeak = mRootObjectWeak.unsafe_get();
151 sp<IBinder> ret = mRootObjectWeak.promote();
152 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
153 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000154}
155
Yifan Hong9734cfc2021-09-13 16:14:09 -0700156std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700157 std::lock_guard<std::mutex> _l(mLock);
158 return mCtx->getCertificate(format);
159}
160
Yifan Hong326afd12021-05-19 15:24:54 -0700161static void joinRpcServer(sp<RpcServer>&& thiz) {
162 thiz->join();
163}
164
165void RpcServer::start() {
166 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
167 std::lock_guard<std::mutex> _l(mLock);
168 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
169 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
170}
171
Steven Moreland611d15f2021-05-01 01:28:27 +0000172void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700173 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
174
175 {
176 std::lock_guard<std::mutex> _l(mLock);
177 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
178 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
179 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700180 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700181 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000182 }
Yifan Hong1a235852021-05-13 16:07:47 -0700183
Steven Moreland2b4f3802021-05-22 01:46:27 +0000184 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000185 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700186 sockaddr_storage addr;
187 socklen_t addrLen = sizeof(addr);
188
189 unique_fd clientFd(
190 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(&addr),
191 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
192
193 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(addr)), "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000194
195 if (clientFd < 0) {
196 ALOGE("Could not accept4 socket: %s", strerror(errno));
197 continue;
198 }
199 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
200
201 {
202 std::lock_guard<std::mutex> _l(mLock);
203 std::thread thread =
204 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
Steven Moreland51c44a92021-10-14 16:50:35 -0700205 std::move(clientFd), addr, addrLen);
Steven Moreland410325a2021-06-02 18:37:42 +0000206 mConnectingThreads[thread.get_id()] = std::move(thread);
207 }
Yifan Hong1a235852021-05-13 16:07:47 -0700208 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000209 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700210
211 {
212 std::lock_guard<std::mutex> _l(mLock);
213 mJoinThreadRunning = false;
214 }
215 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000216}
217
Yifan Hong1a235852021-05-13 16:07:47 -0700218bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700219 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000220 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000221 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000222 return false;
223 }
Yifan Hong1a235852021-05-13 16:07:47 -0700224
225 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700226
Steven Morelanda8b44292021-06-08 01:27:53 +0000227 for (auto& [id, session] : mSessions) {
228 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700229 // server lock is a more general lock
230 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000231 session->mShutdownTrigger->trigger();
232 }
233
Steven Morelandee3f4662021-05-22 01:07:33 +0000234 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000235 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
236 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
237 "Connecting threads: "
238 "%zu, Sessions: %zu. Is your server deadlocked?",
239 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
240 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000241 }
Yifan Hong1a235852021-05-13 16:07:47 -0700242
Yifan Hong326afd12021-05-19 15:24:54 -0700243 // At this point, we know join() is about to exit, but the thread that calls
244 // join() may not have exited yet.
245 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
246 // otherwise ~thread() may call std::terminate(), which may crash the process.
247 // If RpcServer does not own the join thread (aka join() is called directly),
248 // then the owner of RpcServer is responsible for cleaning up that thread.
249 if (mJoinThread.get()) {
250 mJoinThread->join();
251 mJoinThread.reset();
252 }
253
Steven Moreland1c943ec2021-07-13 23:57:56 +0000254 LOG_RPC_DETAIL("Finished waiting on shutdown.");
255
Yifan Hong1a235852021-05-13 16:07:47 -0700256 mShutdownTrigger = nullptr;
257 return true;
258}
259
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000261 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262 std::vector<sp<RpcSession>> sessions;
263 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000264 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000266 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000268}
269
Steven Morelandd539fbf2021-05-05 23:40:25 +0000270size_t RpcServer::numUninitializedSessions() {
271 std::lock_guard<std::mutex> _l(mLock);
272 return mConnectingThreads.size();
273}
274
Steven Moreland51c44a92021-10-14 16:50:35 -0700275void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
276 const sockaddr_storage addr, socklen_t addrLen) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000277 // TODO(b/183988761): cannot trust this simple ID
Yifan Hongb3005502021-05-19 15:37:00 -0700278 LOG_ALWAYS_FATAL_IF(!server->mAgreedExperimental, "no!");
Steven Moreland9d11b922021-05-20 01:22:58 +0000279
280 // mShutdownTrigger can only be cleared once connection threads have joined.
281 // It must be set before this thread is started
282 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700283 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
284
285 status_t status = OK;
286
287 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700288 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700289 if (client == nullptr) {
290 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
291 status = DEAD_OBJECT;
292 // still need to cleanup before we can return
293 } else {
294 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
295 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000296
Steven Moreland659416d2021-05-11 00:47:50 +0000297 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700298 if (status == OK) {
Yifan Hong8c950422021-08-05 17:13:55 -0700299 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &header,
Steven Moreland43921d52021-09-27 17:15:56 -0700300 sizeof(header), {});
Yifan Hong702115c2021-06-24 15:39:18 -0700301 if (status != OK) {
302 ALOGE("Failed to read ID for client connecting to RPC server: %s",
303 statusToString(status).c_str());
304 // still need to cleanup before we can return
305 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000306 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700307
Steven Moreland826367f2021-09-10 14:05:31 -0700308 std::vector<uint8_t> sessionId;
309 if (status == OK) {
310 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700311 if (header.sessionIdSize == kSessionIdBytes) {
312 sessionId.resize(header.sessionIdSize);
313 status = client->interruptableReadFully(server->mShutdownTrigger.get(),
314 sessionId.data(), sessionId.size(), {});
315 if (status != OK) {
316 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
317 statusToString(status).c_str());
318 // still need to cleanup before we can return
319 }
320 } else {
321 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
322 kSessionIdBytes, header.sessionIdSize);
323 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700324 }
325 }
326 }
327
Steven Morelandbf57bce2021-07-26 15:26:12 -0700328 bool incoming = false;
329 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700330 bool requestingNewSession = false;
331
332 if (status == OK) {
333 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
334 protocolVersion = std::min(header.version,
335 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700336 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700337
338 if (requestingNewSession) {
339 RpcNewSessionResponse response{
340 .version = protocolVersion,
341 };
342
Yifan Hong8c950422021-08-05 17:13:55 -0700343 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &response,
Steven Moreland43921d52021-09-27 17:15:56 -0700344 sizeof(response), {});
Steven Morelandbf57bce2021-07-26 15:26:12 -0700345 if (status != OK) {
346 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
347 // still need to cleanup before we can return
348 }
349 }
350 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000351
352 std::thread thisThread;
353 sp<RpcSession> session;
354 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000355 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000356
Yifan Hongb3005502021-05-19 15:37:00 -0700357 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
358 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000359 "Must establish connection on owned thread");
360 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000361 ScopeGuard detachGuard = [&]() {
362 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000363 _l.unlock();
364 server->mShutdownCv.notify_all();
365 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000366 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000367
Steven Morelandbf57bce2021-07-26 15:26:12 -0700368 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000369 return;
370 }
371
Steven Morelandbf57bce2021-07-26 15:26:12 -0700372 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000373 if (incoming) {
374 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000375 return;
376 }
377
Steven Moreland826367f2021-09-10 14:05:31 -0700378 // Uniquely identify session at the application layer. Even if a
379 // client/server use the same certificates, if they create multiple
380 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700381 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000382 size_t tries = 0;
383 do {
384 // don't block if there is some entropy issue
385 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700386 ALOGE("Cannot find new address: %s",
387 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000388 return;
389 }
390
Steven Moreland826367f2021-09-10 14:05:31 -0700391 base::unique_fd fd(TEMP_FAILURE_RETRY(
392 open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
393 if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
394 ALOGE("Could not read from /dev/urandom to create session ID");
395 return;
396 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000397 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000398
399 session = RpcSession::make();
Yifan Hong10423062021-10-08 16:26:32 -0700400 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700401 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700402
403 // if null, falls back to server root
404 sp<IBinder> sessionSpecificRoot;
405 if (server->mRootObjectFactory != nullptr) {
406 sessionSpecificRoot =
407 server->mRootObjectFactory(reinterpret_cast<const sockaddr*>(&addr),
408 addrLen);
409 if (sessionSpecificRoot == nullptr) {
410 ALOGE("Warning: server returned null from root object factory");
411 }
412 }
413
Steven Morelanda8b44292021-06-08 01:27:53 +0000414 if (!session->setForServer(server,
415 sp<RpcServer::EventListener>::fromExisting(
416 static_cast<RpcServer::EventListener*>(
417 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700418 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000419 ALOGE("Failed to attach server to session");
420 return;
421 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000422
Steven Moreland01a6bad2021-06-11 00:59:20 +0000423 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000424 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000425 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700426 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000427 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700428 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000429 return;
430 }
431 session = it->second;
432 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000433
Steven Moreland1b304292021-07-15 22:59:34 +0000434 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700435 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000436 "server state must already be initialized");
437 return;
438 }
439
Steven Moreland5802c2b2021-05-12 20:13:04 +0000440 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000441 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000442 }
443
Yifan Hong702115c2021-06-24 15:39:18 -0700444 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000445
Steven Morelanda63ff932021-05-12 00:03:15 +0000446 // avoid strong cycle
447 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000448
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000449 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000450}
451
Steven Moreland2372f9d2021-08-05 15:42:01 -0700452status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000453 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700454 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000455
Yifan Hongb675ffe2021-08-05 16:37:17 -0700456 unique_fd serverFd(TEMP_FAILURE_RETRY(
457 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000458 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700459 int savedErrno = errno;
460 ALOGE("Could not create socket: %s", strerror(savedErrno));
461 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000462 }
463
464 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
465 int savedErrno = errno;
466 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700467 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000468 }
469
Yifan Honge96a1f12021-07-13 16:08:28 -0700470 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
471 // the backlog is increased to a large number.
472 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
473 // to 1.
474 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000475 int savedErrno = errno;
476 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700477 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000478 }
479
Steven Moreland704fc1a2021-05-04 23:13:14 +0000480 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
481
Steven Moreland2372f9d2021-08-05 15:42:01 -0700482 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700483 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700484 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700485 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700486 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000487}
488
Steven Morelanddd67b942021-07-23 17:15:41 -0700489void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700490 const std::vector<uint8_t>& id = session->mId;
491 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
492 LOG_RPC_DETAIL("Dropping session with address %s",
493 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000494
495 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700496 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000497 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700498 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000499 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700500 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000501 (void)mSessions.erase(it);
502}
503
Steven Moreland19fc9f72021-06-10 03:57:30 +0000504void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000505 mShutdownCv.notify_all();
506}
507
Yifan Hong0eb5a672021-05-12 18:00:25 -0700508bool RpcServer::hasServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700509 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
Yifan Hong0eb5a672021-05-12 18:00:25 -0700510 std::lock_guard<std::mutex> _l(mLock);
511 return mServer.ok();
512}
513
Yifan Hong00aeb762021-05-12 17:07:36 -0700514unique_fd RpcServer::releaseServer() {
515 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
516 std::lock_guard<std::mutex> _l(mLock);
517 return std::move(mServer);
518}
519
Steven Moreland2372f9d2021-08-05 15:42:01 -0700520status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700521 LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
522 std::lock_guard<std::mutex> _l(mLock);
523 if (mServer.ok()) {
524 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700525 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700526 }
527 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700529}
530
Steven Moreland5553ac42020-11-11 02:14:45 +0000531} // namespace android