• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 
22 #include <thread>
23 #include <vector>
24 
25 #include <android-base/scopeguard.h>
26 #include <binder/Parcel.h>
27 #include <binder/RpcServer.h>
28 #include <log/log.h>
29 #include "RpcState.h"
30 
31 #include "RpcSocketAddress.h"
32 #include "RpcWireFormat.h"
33 
34 namespace android {
35 
36 using base::ScopeGuard;
37 using base::unique_fd;
38 
RpcServer()39 RpcServer::RpcServer() {}
~RpcServer()40 RpcServer::~RpcServer() {}
41 
make()42 sp<RpcServer> RpcServer::make() {
43     return sp<RpcServer>::make();
44 }
45 
iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction()46 void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
47     mAgreedExperimental = true;
48 }
49 
setupUnixDomainServer(const char * path)50 bool RpcServer::setupUnixDomainServer(const char* path) {
51     return setupSocketServer(UnixSocketAddress(path));
52 }
53 
setupVsockServer(unsigned int port)54 bool RpcServer::setupVsockServer(unsigned int port) {
55     // realizing value w/ this type at compile time to avoid ubsan abort
56     constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
57 
58     return setupSocketServer(VsockSocketAddress(kAnyCid, port));
59 }
60 
setupInetServer(unsigned int port,unsigned int * assignedPort)61 bool RpcServer::setupInetServer(unsigned int port, unsigned int* assignedPort) {
62     const char* kAddr = "127.0.0.1";
63 
64     if (assignedPort != nullptr) *assignedPort = 0;
65     auto aiStart = InetSocketAddress::getAddrInfo(kAddr, port);
66     if (aiStart == nullptr) return false;
67     for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
68         InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, kAddr, port);
69         if (!setupSocketServer(socketAddress)) {
70             continue;
71         }
72 
73         LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
74         sockaddr_in addr{};
75         socklen_t len = sizeof(addr);
76         if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
77             int savedErrno = errno;
78             ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
79                   strerror(savedErrno));
80             return false;
81         }
82         LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
83                             static_cast<size_t>(len), sizeof(addr));
84         unsigned int realPort = ntohs(addr.sin_port);
85         LOG_ALWAYS_FATAL_IF(port != 0 && realPort != port,
86                             "Requesting inet server on %s but it is set up on %u.",
87                             socketAddress.toString().c_str(), realPort);
88 
89         if (assignedPort != nullptr) {
90             *assignedPort = realPort;
91         }
92 
93         return true;
94     }
95     ALOGE("None of the socket address resolved for %s:%u can be set up as inet server.", kAddr,
96           port);
97     return false;
98 }
99 
setMaxThreads(size_t threads)100 void RpcServer::setMaxThreads(size_t threads) {
101     LOG_ALWAYS_FATAL_IF(threads <= 0, "RpcServer is useless without threads");
102     LOG_ALWAYS_FATAL_IF(mStarted, "must be called before started");
103     mMaxThreads = threads;
104 }
105 
getMaxThreads()106 size_t RpcServer::getMaxThreads() {
107     return mMaxThreads;
108 }
109 
setRootObject(const sp<IBinder> & binder)110 void RpcServer::setRootObject(const sp<IBinder>& binder) {
111     std::lock_guard<std::mutex> _l(mLock);
112     mRootObjectWeak = mRootObject = binder;
113 }
114 
setRootObjectWeak(const wp<IBinder> & binder)115 void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
116     std::lock_guard<std::mutex> _l(mLock);
117     mRootObject.clear();
118     mRootObjectWeak = binder;
119 }
120 
getRootObject()121 sp<IBinder> RpcServer::getRootObject() {
122     std::lock_guard<std::mutex> _l(mLock);
123     bool hasWeak = mRootObjectWeak.unsafe_get();
124     sp<IBinder> ret = mRootObjectWeak.promote();
125     ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
126     return ret;
127 }
128 
join()129 void RpcServer::join() {
130     while (true) {
131         (void)acceptOne();
132     }
133 }
134 
acceptOne()135 bool RpcServer::acceptOne() {
136     LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
137     LOG_ALWAYS_FATAL_IF(!hasServer(), "RpcServer must be setup to join.");
138 
139     unique_fd clientFd(
140             TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
141 
142     if (clientFd < 0) {
143         ALOGE("Could not accept4 socket: %s", strerror(errno));
144         return false;
145     }
146     LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
147 
148     {
149         std::lock_guard<std::mutex> _l(mLock);
150         std::thread thread =
151                 std::thread(&RpcServer::establishConnection, this,
152                             std::move(sp<RpcServer>::fromExisting(this)), std::move(clientFd));
153         mConnectingThreads[thread.get_id()] = std::move(thread);
154     }
155 
156     return true;
157 }
158 
listSessions()159 std::vector<sp<RpcSession>> RpcServer::listSessions() {
160     std::lock_guard<std::mutex> _l(mLock);
161     std::vector<sp<RpcSession>> sessions;
162     for (auto& [id, session] : mSessions) {
163         (void)id;
164         sessions.push_back(session);
165     }
166     return sessions;
167 }
168 
numUninitializedSessions()169 size_t RpcServer::numUninitializedSessions() {
170     std::lock_guard<std::mutex> _l(mLock);
171     return mConnectingThreads.size();
172 }
173 
establishConnection(sp<RpcServer> && server,base::unique_fd clientFd)174 void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
175     LOG_ALWAYS_FATAL_IF(this != server.get(), "Must pass same ownership object");
176 
177     // TODO(b/183988761): cannot trust this simple ID
178     LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
179     bool idValid = true;
180     int32_t id;
181     if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
182         ALOGE("Could not read ID from fd %d", clientFd.get());
183         idValid = false;
184     }
185 
186     std::thread thisThread;
187     sp<RpcSession> session;
188     {
189         std::lock_guard<std::mutex> _l(mLock);
190 
191         auto threadId = mConnectingThreads.find(std::this_thread::get_id());
192         LOG_ALWAYS_FATAL_IF(threadId == mConnectingThreads.end(),
193                             "Must establish connection on owned thread");
194         thisThread = std::move(threadId->second);
195         ScopeGuard detachGuard = [&]() { thisThread.detach(); };
196         mConnectingThreads.erase(threadId);
197 
198         if (!idValid) {
199             return;
200         }
201 
202         if (id == RPC_SESSION_ID_NEW) {
203             LOG_ALWAYS_FATAL_IF(mSessionIdCounter >= INT32_MAX, "Out of session IDs");
204             mSessionIdCounter++;
205 
206             session = RpcSession::make();
207             session->setForServer(wp<RpcServer>::fromExisting(this), mSessionIdCounter);
208 
209             mSessions[mSessionIdCounter] = session;
210         } else {
211             auto it = mSessions.find(id);
212             if (it == mSessions.end()) {
213                 ALOGE("Cannot add thread, no record of session with ID %d", id);
214                 return;
215             }
216             session = it->second;
217         }
218 
219         detachGuard.Disable();
220         session->preJoin(std::move(thisThread));
221     }
222 
223     // avoid strong cycle
224     server = nullptr;
225     //
226     //
227     // DO NOT ACCESS MEMBER VARIABLES BELOW
228     //
229 
230     session->join(std::move(clientFd));
231 }
232 
setupSocketServer(const RpcSocketAddress & addr)233 bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
234     LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
235     LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
236 
237     unique_fd serverFd(
238             TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
239     if (serverFd == -1) {
240         ALOGE("Could not create socket: %s", strerror(errno));
241         return false;
242     }
243 
244     if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
245         int savedErrno = errno;
246         ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
247         return false;
248     }
249 
250     if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
251         int savedErrno = errno;
252         ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
253         return false;
254     }
255 
256     LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
257 
258     mServer = std::move(serverFd);
259     return true;
260 }
261 
onSessionTerminating(const sp<RpcSession> & session)262 void RpcServer::onSessionTerminating(const sp<RpcSession>& session) {
263     auto id = session->mId;
264     LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
265     LOG_RPC_DETAIL("Dropping session %d", *id);
266 
267     std::lock_guard<std::mutex> _l(mLock);
268     auto it = mSessions.find(*id);
269     LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %d", *id);
270     LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %d", *id);
271     (void)mSessions.erase(it);
272 }
273 
hasServer()274 bool RpcServer::hasServer() {
275     LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
276     std::lock_guard<std::mutex> _l(mLock);
277     return mServer.ok();
278 }
279 
releaseServer()280 unique_fd RpcServer::releaseServer() {
281     LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
282     std::lock_guard<std::mutex> _l(mLock);
283     return std::move(mServer);
284 }
285 
setupExternalServer(base::unique_fd serverFd)286 bool RpcServer::setupExternalServer(base::unique_fd serverFd) {
287     LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
288     std::lock_guard<std::mutex> _l(mLock);
289     if (mServer.ok()) {
290         ALOGE("Each RpcServer can only have one server.");
291         return false;
292     }
293     mServer = std::move(serverFd);
294     return true;
295 }
296 
297 } // namespace android
298