blob: ace5cd5052ed9c66f04d9849c9f81c8d8fac41b9 [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
Steven Moreland2372f9d2021-08-05 15:42:01 -070061status_t RpcServer::setupUnixDomainServer(const char* path) {
Steven Moreland611d15f2021-05-01 01:28:27 +000062 return setupSocketServer(UnixSocketAddress(path));
63}
64
Steven Moreland2372f9d2021-08-05 15:42:01 -070065status_t RpcServer::setupVsockServer(unsigned int port) {
Steven Moreland611d15f2021-05-01 01:28:27 +000066 // realizing value w/ this type at compile time to avoid ubsan abort
67 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
68
69 return setupSocketServer(VsockSocketAddress(kAnyCid, port));
70}
71
Steven Moreland2372f9d2021-08-05 15:42:01 -070072status_t RpcServer::setupInetServer(const char* address, unsigned int port,
73 unsigned int* assignedPort) {
Steven Moreland611d15f2021-05-01 01:28:27 +000074 if (assignedPort != nullptr) *assignedPort = 0;
Devin Mooref3b9c4f2021-08-03 15:50:13 +000075 auto aiStart = InetSocketAddress::getAddrInfo(address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070076 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +000077 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
Devin Mooref3b9c4f2021-08-03 15:50:13 +000078 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, address, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -070079 if (status_t status = setupSocketServer(socketAddress); status != OK) {
Steven Moreland611d15f2021-05-01 01:28:27 +000080 continue;
81 }
82
83 LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
84 sockaddr_in addr{};
85 socklen_t len = sizeof(addr);
86 if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
87 int savedErrno = errno;
88 ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
89 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -070090 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +000091 }
92 LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
93 static_cast<size_t>(len), sizeof(addr));
94 unsigned int realPort = ntohs(addr.sin_port);
95 LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
96 "Requesting inet server on %s but it is set up on %u.",
97 socketAddress.toString().c_str(), realPort);
98
99 if (assignedPort != nullptr) {
100 *assignedPort = realPort;
101 }
102
Steven Moreland2372f9d2021-08-05 15:42:01 -0700103 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000104 }
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000105 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 +0000106 port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700107 return UNKNOWN_ERROR;
Steven Moreland611d15f2021-05-01 01:28:27 +0000108}
109
Steven Morelandf137de92021-04-24 01:54:26 +0000110void RpcServer::setMaxThreads(size_t threads) {
111 LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
Yifan Hong1a235852021-05-13 16:07:47 -0700112 LOG_ALWAYS_FATAL_IF(mJoinThreadRunning, "Cannot set max threads while running");
Steven Morelandf137de92021-04-24 01:54:26 +0000113 mMaxThreads = threads;
114}
115
116size_t RpcServer::getMaxThreads() {
117 return mMaxThreads;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118}
119
Steven Morelandbf57bce2021-07-26 15:26:12 -0700120void RpcServer::setProtocolVersion(uint32_t version) {
121 mProtocolVersion = version;
122}
123
Steven Moreland5553ac42020-11-11 02:14:45 +0000124void RpcServer::setRootObject(const sp<IBinder>& binder) {
Steven Morelandebafe332021-04-24 00:24:35 +0000125 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland51c44a92021-10-14 16:50:35 -0700126 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700127 mRootObjectWeak = mRootObject = binder;
128}
129
130void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
131 std::lock_guard<std::mutex> _l(mLock);
132 mRootObject.clear();
Steven Moreland51c44a92021-10-14 16:50:35 -0700133 mRootObjectFactory = nullptr;
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700134 mRootObjectWeak = binder;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135}
Steven Moreland51c44a92021-10-14 16:50:35 -0700136void RpcServer::setPerSessionRootObject(
137 std::function<sp<IBinder>(const sockaddr*, socklen_t)>&& makeObject) {
138 std::lock_guard<std::mutex> _l(mLock);
139 mRootObject.clear();
140 mRootObjectWeak.clear();
141 mRootObjectFactory = std::move(makeObject);
142}
Steven Moreland5553ac42020-11-11 02:14:45 +0000143
144sp<IBinder> RpcServer::getRootObject() {
Steven Morelandebafe332021-04-24 00:24:35 +0000145 std::lock_guard<std::mutex> _l(mLock);
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700146 bool hasWeak = mRootObjectWeak.unsafe_get();
147 sp<IBinder> ret = mRootObjectWeak.promote();
148 ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
149 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000150}
151
Yifan Hong9734cfc2021-09-13 16:14:09 -0700152std::vector<uint8_t> RpcServer::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700153 std::lock_guard<std::mutex> _l(mLock);
154 return mCtx->getCertificate(format);
155}
156
Yifan Hong326afd12021-05-19 15:24:54 -0700157static void joinRpcServer(sp<RpcServer>&& thiz) {
158 thiz->join();
159}
160
161void RpcServer::start() {
Yifan Hong326afd12021-05-19 15:24:54 -0700162 std::lock_guard<std::mutex> _l(mLock);
163 LOG_ALWAYS_FATAL_IF(mJoinThread.get(), "Already started!");
164 mJoinThread = std::make_unique<std::thread>(&joinRpcServer, sp<RpcServer>::fromExisting(this));
165}
166
Steven Moreland611d15f2021-05-01 01:28:27 +0000167void RpcServer::join() {
Yifan Hong1a235852021-05-13 16:07:47 -0700168
169 {
170 std::lock_guard<std::mutex> _l(mLock);
171 LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
172 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
173 mJoinThreadRunning = true;
Yifan Hong8c950422021-08-05 17:13:55 -0700174 mShutdownTrigger = FdTrigger::make();
Yifan Hong1a235852021-05-13 16:07:47 -0700175 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
Steven Morelandd539fbf2021-05-05 23:40:25 +0000176 }
Yifan Hong1a235852021-05-13 16:07:47 -0700177
Steven Moreland2b4f3802021-05-22 01:46:27 +0000178 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000179 while ((status = mShutdownTrigger->triggerablePoll(mServer, POLLIN)) == OK) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700180 sockaddr_storage addr;
181 socklen_t addrLen = sizeof(addr);
182
183 unique_fd clientFd(
184 TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(&addr),
185 &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
186
187 LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(addr)), "Truncated address");
Steven Moreland410325a2021-06-02 18:37:42 +0000188
189 if (clientFd < 0) {
190 ALOGE("Could not accept4 socket: %s", strerror(errno));
191 continue;
192 }
193 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
194
195 {
196 std::lock_guard<std::mutex> _l(mLock);
197 std::thread thread =
198 std::thread(&RpcServer::establishConnection, sp<RpcServer>::fromExisting(this),
Steven Moreland51c44a92021-10-14 16:50:35 -0700199 std::move(clientFd), addr, addrLen);
Steven Moreland410325a2021-06-02 18:37:42 +0000200 mConnectingThreads[thread.get_id()] = std::move(thread);
201 }
Yifan Hong1a235852021-05-13 16:07:47 -0700202 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000203 LOG_RPC_DETAIL("RpcServer::join exiting with %s", statusToString(status).c_str());
Yifan Hong1a235852021-05-13 16:07:47 -0700204
205 {
206 std::lock_guard<std::mutex> _l(mLock);
207 mJoinThreadRunning = false;
208 }
209 mShutdownCv.notify_all();
Steven Morelandd539fbf2021-05-05 23:40:25 +0000210}
211
Yifan Hong1a235852021-05-13 16:07:47 -0700212bool RpcServer::shutdown() {
Yifan Hong1a235852021-05-13 16:07:47 -0700213 std::unique_lock<std::mutex> _l(mLock);
Steven Moreland9d11b922021-05-20 01:22:58 +0000214 if (mShutdownTrigger == nullptr) {
Steven Moreland1c943ec2021-07-13 23:57:56 +0000215 LOG_RPC_DETAIL("Cannot shutdown. No shutdown trigger installed (already shutdown?)");
Steven Moreland9d11b922021-05-20 01:22:58 +0000216 return false;
217 }
Yifan Hong1a235852021-05-13 16:07:47 -0700218
219 mShutdownTrigger->trigger();
Steven Morelandab3f4422021-09-27 18:38:20 -0700220
Steven Morelanda8b44292021-06-08 01:27:53 +0000221 for (auto& [id, session] : mSessions) {
222 (void)id;
Steven Morelandab3f4422021-09-27 18:38:20 -0700223 // server lock is a more general lock
224 std::lock_guard<std::mutex> _lSession(session->mMutex);
Steven Morelanda8b44292021-06-08 01:27:53 +0000225 session->mShutdownTrigger->trigger();
226 }
227
Steven Morelandee3f4662021-05-22 01:07:33 +0000228 while (mJoinThreadRunning || !mConnectingThreads.empty() || !mSessions.empty()) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000229 if (std::cv_status::timeout == mShutdownCv.wait_for(_l, std::chrono::seconds(1))) {
230 ALOGE("Waiting for RpcServer to shut down (1s w/o progress). Join thread running: %d, "
231 "Connecting threads: "
232 "%zu, Sessions: %zu. Is your server deadlocked?",
233 mJoinThreadRunning, mConnectingThreads.size(), mSessions.size());
234 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000235 }
Yifan Hong1a235852021-05-13 16:07:47 -0700236
Yifan Hong326afd12021-05-19 15:24:54 -0700237 // At this point, we know join() is about to exit, but the thread that calls
238 // join() may not have exited yet.
239 // If RpcServer owns the join thread (aka start() is called), make sure the thread exits;
240 // otherwise ~thread() may call std::terminate(), which may crash the process.
241 // If RpcServer does not own the join thread (aka join() is called directly),
242 // then the owner of RpcServer is responsible for cleaning up that thread.
243 if (mJoinThread.get()) {
244 mJoinThread->join();
245 mJoinThread.reset();
246 }
247
Steven Moreland1c943ec2021-07-13 23:57:56 +0000248 LOG_RPC_DETAIL("Finished waiting on shutdown.");
249
Yifan Hong1a235852021-05-13 16:07:47 -0700250 mShutdownTrigger = nullptr;
251 return true;
252}
253
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000254std::vector<sp<RpcSession>> RpcServer::listSessions() {
Steven Moreland611d15f2021-05-01 01:28:27 +0000255 std::lock_guard<std::mutex> _l(mLock);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 std::vector<sp<RpcSession>> sessions;
257 for (auto& [id, session] : mSessions) {
Steven Moreland736664b2021-05-01 04:27:25 +0000258 (void)id;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259 sessions.push_back(session);
Steven Moreland736664b2021-05-01 04:27:25 +0000260 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 return sessions;
Steven Moreland611d15f2021-05-01 01:28:27 +0000262}
263
Steven Morelandd539fbf2021-05-05 23:40:25 +0000264size_t RpcServer::numUninitializedSessions() {
265 std::lock_guard<std::mutex> _l(mLock);
266 return mConnectingThreads.size();
267}
268
Steven Moreland51c44a92021-10-14 16:50:35 -0700269void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd,
270 const sockaddr_storage addr, socklen_t addrLen) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000271 // mShutdownTrigger can only be cleared once connection threads have joined.
272 // It must be set before this thread is started
273 LOG_ALWAYS_FATAL_IF(server->mShutdownTrigger == nullptr);
Yifan Hong702115c2021-06-24 15:39:18 -0700274 LOG_ALWAYS_FATAL_IF(server->mCtx == nullptr);
275
276 status_t status = OK;
277
278 int clientFdForLog = clientFd.get();
Yifan Hongf6d42292021-08-05 23:43:05 -0700279 auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700280 if (client == nullptr) {
281 ALOGE("Dropping accept4()-ed socket because sslAccept fails");
282 status = DEAD_OBJECT;
283 // still need to cleanup before we can return
284 } else {
285 LOG_RPC_DETAIL("Created RpcTransport %p for client fd %d", client.get(), clientFdForLog);
286 }
Steven Moreland9d11b922021-05-20 01:22:58 +0000287
Steven Moreland659416d2021-05-11 00:47:50 +0000288 RpcConnectionHeader header;
Yifan Hong702115c2021-06-24 15:39:18 -0700289 if (status == OK) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000290 iovec iov{&header, sizeof(header)};
291 status = client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1, {});
Yifan Hong702115c2021-06-24 15:39:18 -0700292 if (status != OK) {
293 ALOGE("Failed to read ID for client connecting to RPC server: %s",
294 statusToString(status).c_str());
295 // still need to cleanup before we can return
296 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000297 }
Steven Morelandbf57bce2021-07-26 15:26:12 -0700298
Steven Moreland826367f2021-09-10 14:05:31 -0700299 std::vector<uint8_t> sessionId;
300 if (status == OK) {
301 if (header.sessionIdSize > 0) {
Steven Morelandc5032042021-09-30 15:40:27 -0700302 if (header.sessionIdSize == kSessionIdBytes) {
303 sessionId.resize(header.sessionIdSize);
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000304 iovec iov{sessionId.data(), sessionId.size()};
305 status =
306 client->interruptableReadFully(server->mShutdownTrigger.get(), &iov, 1, {});
Steven Morelandc5032042021-09-30 15:40:27 -0700307 if (status != OK) {
308 ALOGE("Failed to read session ID for client connecting to RPC server: %s",
309 statusToString(status).c_str());
310 // still need to cleanup before we can return
311 }
312 } else {
313 ALOGE("Malformed session ID. Expecting session ID of size %zu but got %" PRIu16,
314 kSessionIdBytes, header.sessionIdSize);
315 status = BAD_VALUE;
Steven Moreland826367f2021-09-10 14:05:31 -0700316 }
317 }
318 }
319
Steven Morelandbf57bce2021-07-26 15:26:12 -0700320 bool incoming = false;
321 uint32_t protocolVersion = 0;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700322 bool requestingNewSession = false;
323
324 if (status == OK) {
325 incoming = header.options & RPC_CONNECTION_OPTION_INCOMING;
326 protocolVersion = std::min(header.version,
327 server->mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION));
Steven Moreland826367f2021-09-10 14:05:31 -0700328 requestingNewSession = sessionId.empty();
Steven Morelandbf57bce2021-07-26 15:26:12 -0700329
330 if (requestingNewSession) {
331 RpcNewSessionResponse response{
332 .version = protocolVersion,
333 };
334
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000335 iovec iov{&response, sizeof(response)};
336 status = client->interruptableWriteFully(server->mShutdownTrigger.get(), &iov, 1, {});
Steven Morelandbf57bce2021-07-26 15:26:12 -0700337 if (status != OK) {
338 ALOGE("Failed to send new session response: %s", statusToString(status).c_str());
339 // still need to cleanup before we can return
340 }
341 }
342 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000343
344 std::thread thisThread;
345 sp<RpcSession> session;
346 {
Steven Moreland9d11b922021-05-20 01:22:58 +0000347 std::unique_lock<std::mutex> _l(server->mLock);
Steven Morelanda63ff932021-05-12 00:03:15 +0000348
Yifan Hongb3005502021-05-19 15:37:00 -0700349 auto threadId = server->mConnectingThreads.find(std::this_thread::get_id());
350 LOG_ALWAYS_FATAL_IF(threadId == server->mConnectingThreads.end(),
Steven Morelanda63ff932021-05-12 00:03:15 +0000351 "Must establish connection on owned thread");
352 thisThread = std::move(threadId->second);
Steven Morelandadc5dca2021-05-25 02:06:03 +0000353 ScopeGuard detachGuard = [&]() {
354 thisThread.detach();
Steven Moreland9d11b922021-05-20 01:22:58 +0000355 _l.unlock();
356 server->mShutdownCv.notify_all();
357 };
Steven Morelandadc5dca2021-05-25 02:06:03 +0000358 server->mConnectingThreads.erase(threadId);
Steven Moreland9d11b922021-05-20 01:22:58 +0000359
Steven Morelandbf57bce2021-07-26 15:26:12 -0700360 if (status != OK || server->mShutdownTrigger->isTriggered()) {
Steven Moreland5802c2b2021-05-12 20:13:04 +0000361 return;
362 }
363
Steven Morelandbf57bce2021-07-26 15:26:12 -0700364 if (requestingNewSession) {
Steven Moreland1b304292021-07-15 22:59:34 +0000365 if (incoming) {
366 ALOGE("Cannot create a new session with an incoming connection, would leak");
Steven Moreland659416d2021-05-11 00:47:50 +0000367 return;
368 }
369
Steven Moreland826367f2021-09-10 14:05:31 -0700370 // Uniquely identify session at the application layer. Even if a
371 // client/server use the same certificates, if they create multiple
372 // sessions, we still want to distinguish between them.
Steven Morelandc5032042021-09-30 15:40:27 -0700373 sessionId.resize(kSessionIdBytes);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000374 size_t tries = 0;
375 do {
376 // don't block if there is some entropy issue
377 if (tries++ > 5) {
Steven Moreland826367f2021-09-10 14:05:31 -0700378 ALOGE("Cannot find new address: %s",
379 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000380 return;
381 }
382
Steven Moreland826367f2021-09-10 14:05:31 -0700383 base::unique_fd fd(TEMP_FAILURE_RETRY(
384 open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
385 if (!base::ReadFully(fd, sessionId.data(), sessionId.size())) {
386 ALOGE("Could not read from /dev/urandom to create session ID");
387 return;
388 }
Steven Moreland01a6bad2021-06-11 00:59:20 +0000389 } while (server->mSessions.end() != server->mSessions.find(sessionId));
Steven Morelanda63ff932021-05-12 00:03:15 +0000390
391 session = RpcSession::make();
Yifan Hong10423062021-10-08 16:26:32 -0700392 session->setMaxIncomingThreads(server->mMaxThreads);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700393 if (!session->setProtocolVersion(protocolVersion)) return;
Steven Moreland51c44a92021-10-14 16:50:35 -0700394
395 // if null, falls back to server root
396 sp<IBinder> sessionSpecificRoot;
397 if (server->mRootObjectFactory != nullptr) {
398 sessionSpecificRoot =
399 server->mRootObjectFactory(reinterpret_cast<const sockaddr*>(&addr),
400 addrLen);
401 if (sessionSpecificRoot == nullptr) {
402 ALOGE("Warning: server returned null from root object factory");
403 }
404 }
405
Steven Morelanda8b44292021-06-08 01:27:53 +0000406 if (!session->setForServer(server,
407 sp<RpcServer::EventListener>::fromExisting(
408 static_cast<RpcServer::EventListener*>(
409 server.get())),
Steven Moreland51c44a92021-10-14 16:50:35 -0700410 sessionId, sessionSpecificRoot)) {
Steven Morelanda8b44292021-06-08 01:27:53 +0000411 ALOGE("Failed to attach server to session");
412 return;
413 }
Steven Morelanda63ff932021-05-12 00:03:15 +0000414
Steven Moreland01a6bad2021-06-11 00:59:20 +0000415 server->mSessions[sessionId] = session;
Steven Morelanda63ff932021-05-12 00:03:15 +0000416 } else {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000417 auto it = server->mSessions.find(sessionId);
Yifan Hongb3005502021-05-19 15:37:00 -0700418 if (it == server->mSessions.end()) {
Steven Moreland01a6bad2021-06-11 00:59:20 +0000419 ALOGE("Cannot add thread, no record of session with ID %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700420 base::HexString(sessionId.data(), sessionId.size()).c_str());
Steven Morelanda63ff932021-05-12 00:03:15 +0000421 return;
422 }
423 session = it->second;
424 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000425
Steven Moreland1b304292021-07-15 22:59:34 +0000426 if (incoming) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700427 LOG_ALWAYS_FATAL_IF(OK != session->addOutgoingConnection(std::move(client), true),
Steven Moreland659416d2021-05-11 00:47:50 +0000428 "server state must already be initialized");
429 return;
430 }
431
Steven Moreland5802c2b2021-05-12 20:13:04 +0000432 detachGuard.Disable();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000433 session->preJoinThreadOwnership(std::move(thisThread));
Steven Morelanda63ff932021-05-12 00:03:15 +0000434 }
435
Yifan Hong702115c2021-06-24 15:39:18 -0700436 auto setupResult = session->preJoinSetup(std::move(client));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000437
Steven Morelanda63ff932021-05-12 00:03:15 +0000438 // avoid strong cycle
439 server = nullptr;
Steven Morelanda63ff932021-05-12 00:03:15 +0000440
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000441 RpcSession::join(std::move(session), std::move(setupResult));
Steven Morelanda63ff932021-05-12 00:03:15 +0000442}
443
Steven Moreland2372f9d2021-08-05 15:42:01 -0700444status_t RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
Steven Moreland704fc1a2021-05-04 23:13:14 +0000445 LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
Yifan Hong0eb5a672021-05-12 18:00:25 -0700446 LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
Steven Moreland611d15f2021-05-01 01:28:27 +0000447
Yifan Hongb675ffe2021-08-05 16:37:17 -0700448 unique_fd serverFd(TEMP_FAILURE_RETRY(
449 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland611d15f2021-05-01 01:28:27 +0000450 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700451 int savedErrno = errno;
452 ALOGE("Could not create socket: %s", strerror(savedErrno));
453 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000454 }
455
456 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
457 int savedErrno = errno;
458 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700459 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000460 }
461
Yifan Honge96a1f12021-07-13 16:08:28 -0700462 // Right now, we create all threads at once, making accept4 slow. To avoid hanging the client,
463 // the backlog is increased to a large number.
464 // TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
465 // to 1.
466 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000467 int savedErrno = errno;
468 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700469 return -savedErrno;
Steven Moreland611d15f2021-05-01 01:28:27 +0000470 }
471
Steven Moreland704fc1a2021-05-04 23:13:14 +0000472 LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
473
Steven Moreland2372f9d2021-08-05 15:42:01 -0700474 if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
Yifan Hongc276f8d2021-05-13 17:13:44 -0700475 ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700476 return status;
Yifan Hongc276f8d2021-05-13 17:13:44 -0700477 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700478 return OK;
Steven Moreland611d15f2021-05-01 01:28:27 +0000479}
480
Steven Morelanddd67b942021-07-23 17:15:41 -0700481void RpcServer::onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) {
Steven Moreland826367f2021-09-10 14:05:31 -0700482 const std::vector<uint8_t>& id = session->mId;
483 LOG_ALWAYS_FATAL_IF(id.empty(), "Server sessions must be initialized with ID");
484 LOG_RPC_DETAIL("Dropping session with address %s",
485 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000486
487 std::lock_guard<std::mutex> _l(mLock);
Steven Moreland826367f2021-09-10 14:05:31 -0700488 auto it = mSessions.find(id);
Steven Moreland01a6bad2021-06-11 00:59:20 +0000489 LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700490 base::HexString(id.data(), id.size()).c_str());
Steven Moreland01a6bad2021-06-11 00:59:20 +0000491 LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %s",
Steven Moreland826367f2021-09-10 14:05:31 -0700492 base::HexString(id.data(), id.size()).c_str());
Steven Morelandee78e762021-05-05 21:12:51 +0000493 (void)mSessions.erase(it);
494}
495
Steven Moreland19fc9f72021-06-10 03:57:30 +0000496void RpcServer::onSessionIncomingThreadEnded() {
Steven Morelandee3f4662021-05-22 01:07:33 +0000497 mShutdownCv.notify_all();
498}
499
Yifan Hong0eb5a672021-05-12 18:00:25 -0700500bool RpcServer::hasServer() {
501 std::lock_guard<std::mutex> _l(mLock);
502 return mServer.ok();
503}
504
Yifan Hong00aeb762021-05-12 17:07:36 -0700505unique_fd RpcServer::releaseServer() {
Yifan Hong00aeb762021-05-12 17:07:36 -0700506 std::lock_guard<std::mutex> _l(mLock);
507 return std::move(mServer);
508}
509
Steven Moreland2372f9d2021-08-05 15:42:01 -0700510status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700511 std::lock_guard<std::mutex> _l(mLock);
512 if (mServer.ok()) {
513 ALOGE("Each RpcServer can only have one server.");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700514 return INVALID_OPERATION;
Yifan Hong00aeb762021-05-12 17:07:36 -0700515 }
516 mServer = std::move(serverFd);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700517 return OK;
Yifan Hong00aeb762021-05-12 17:07:36 -0700518}
519
Steven Moreland5553ac42020-11-11 02:14:45 +0000520} // namespace android