xref: /aosp_15_r20/frameworks/native/libs/binder/libbinder_rpc_unstable.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright (C) 2021 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 #include <binder_rpc_unstable.hpp>
18 
19 #include <android/binder_libbinder.h>
20 #include <binder/RpcServer.h>
21 #include <binder/RpcSession.h>
22 #include <binder/unique_fd.h>
23 
24 #ifndef __TRUSTY__
25 #include <cutils/sockets.h>
26 #endif
27 
28 #ifdef __linux__
29 #include <linux/vm_sockets.h>
30 #endif // __linux__
31 
32 using android::OK;
33 using android::RpcServer;
34 using android::RpcSession;
35 using android::sp;
36 using android::status_t;
37 using android::statusToString;
38 using android::binder::unique_fd;
39 
40 // Opaque handle for RpcServer.
41 struct ARpcServer {};
42 
43 // Opaque handle for RpcSession.
44 struct ARpcSession {};
45 
46 template <typename A, typename T>
createObjectHandle(sp<T> & server)47 static A* createObjectHandle(sp<T>& server) {
48     auto ref = server.get();
49     ref->incStrong(ref);
50     return reinterpret_cast<A*>(ref);
51 }
52 
53 template <typename T, typename A>
freeObjectHandle(A * handle)54 static void freeObjectHandle(A* handle) {
55     LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
56     auto ref = reinterpret_cast<T*>(handle);
57     ref->decStrong(ref);
58 }
59 
60 template <typename T, typename A>
handleToStrongPointer(A * handle)61 static sp<T> handleToStrongPointer(A* handle) {
62     LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
63     auto ref = reinterpret_cast<T*>(handle);
64     return sp<T>::fromExisting(ref);
65 }
66 
toTransportMode(ARpcSession_FileDescriptorTransportMode mode)67 RpcSession::FileDescriptorTransportMode toTransportMode(
68         ARpcSession_FileDescriptorTransportMode mode) {
69     switch (mode) {
70         case ARpcSession_FileDescriptorTransportMode::None:
71             return RpcSession::FileDescriptorTransportMode::NONE;
72         case ARpcSession_FileDescriptorTransportMode::Unix:
73             return RpcSession::FileDescriptorTransportMode::UNIX;
74         case ARpcSession_FileDescriptorTransportMode::Trusty:
75             return RpcSession::FileDescriptorTransportMode::TRUSTY;
76         default:
77             return RpcSession::FileDescriptorTransportMode::NONE;
78     }
79 }
80 
81 extern "C" {
82 
83 #ifndef __TRUSTY__
ARpcServer_newVsock(AIBinder * service,unsigned int cid,unsigned int port,unsigned int * assignedPort)84 ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int cid, unsigned int port,
85                                 unsigned int* assignedPort) {
86     auto server = RpcServer::make();
87 
88     unsigned int bindCid = VMADDR_CID_ANY; // bind to the remote interface
89     if (cid == VMADDR_CID_LOCAL) {
90         bindCid = VMADDR_CID_LOCAL; // bind to the local interface
91         cid = VMADDR_CID_ANY;       // no need for a connection filter
92     }
93 
94     if (status_t status = server->setupVsockServer(bindCid, port, assignedPort); status != OK) {
95         ALOGE("Failed to set up vsock server with port %u error: %s", port,
96               statusToString(status).c_str());
97         return nullptr;
98     }
99     if (cid != VMADDR_CID_ANY) {
100         server->setConnectionFilter([=](const void* addr, size_t addrlen) {
101             LOG_ALWAYS_FATAL_IF(addrlen < sizeof(sockaddr_vm), "sockaddr is truncated");
102             const sockaddr_vm* vaddr = reinterpret_cast<const sockaddr_vm*>(addr);
103             LOG_ALWAYS_FATAL_IF(vaddr->svm_family != AF_VSOCK, "address is not a vsock");
104             if (cid != vaddr->svm_cid) {
105                 ALOGE("Rejected vsock connection from CID %u", vaddr->svm_cid);
106                 return false;
107             }
108             return true;
109         });
110     }
111     server->setRootObject(AIBinder_toPlatformBinder(service));
112     return createObjectHandle<ARpcServer>(server);
113 }
114 
ARpcServer_newBoundSocket(AIBinder * service,int socketFd)115 ARpcServer* ARpcServer_newBoundSocket(AIBinder* service, int socketFd) {
116     auto server = RpcServer::make();
117     auto fd = unique_fd(socketFd);
118     if (!fd.ok()) {
119         ALOGE("Invalid socket fd %d", socketFd);
120         return nullptr;
121     }
122     if (status_t status = server->setupRawSocketServer(std::move(fd)); status != OK) {
123         ALOGE("Failed to set up RPC server with fd %d error: %s", socketFd,
124               statusToString(status).c_str());
125         return nullptr;
126     }
127     server->setRootObject(AIBinder_toPlatformBinder(service));
128     return createObjectHandle<ARpcServer>(server);
129 }
130 
ARpcServer_newUnixDomainBootstrap(AIBinder * service,int bootstrapFd)131 ARpcServer* ARpcServer_newUnixDomainBootstrap(AIBinder* service, int bootstrapFd) {
132     auto server = RpcServer::make();
133     auto fd = unique_fd(bootstrapFd);
134     if (!fd.ok()) {
135         ALOGE("Invalid bootstrap fd %d", bootstrapFd);
136         return nullptr;
137     }
138     if (status_t status = server->setupUnixDomainSocketBootstrapServer(std::move(fd));
139         status != OK) {
140         ALOGE("Failed to set up Unix Domain RPC server with bootstrap fd %d error: %s", bootstrapFd,
141               statusToString(status).c_str());
142         return nullptr;
143     }
144     server->setRootObject(AIBinder_toPlatformBinder(service));
145     return createObjectHandle<ARpcServer>(server);
146 }
147 
ARpcServer_newInet(AIBinder * service,const char * address,unsigned int port)148 ARpcServer* ARpcServer_newInet(AIBinder* service, const char* address, unsigned int port) {
149     auto server = RpcServer::make();
150     if (status_t status = server->setupInetServer(address, port, nullptr); status != OK) {
151         ALOGE("Failed to set up inet RPC server with address %s and port %u error: %s", address,
152               port, statusToString(status).c_str());
153         return nullptr;
154     }
155     server->setRootObject(AIBinder_toPlatformBinder(service));
156     return createObjectHandle<ARpcServer>(server);
157 }
158 #endif // __TRUSTY__
159 
ARpcServer_setSupportedFileDescriptorTransportModes(ARpcServer * handle,const ARpcSession_FileDescriptorTransportMode modes[],size_t modes_len)160 void ARpcServer_setSupportedFileDescriptorTransportModes(
161         ARpcServer* handle, const ARpcSession_FileDescriptorTransportMode modes[],
162         size_t modes_len) {
163     auto server = handleToStrongPointer<RpcServer>(handle);
164     std::vector<RpcSession::FileDescriptorTransportMode> modevec;
165     for (size_t i = 0; i < modes_len; i++) {
166         modevec.push_back(toTransportMode(modes[i]));
167     }
168     server->setSupportedFileDescriptorTransportModes(modevec);
169 }
170 
ARpcServer_setMaxThreads(ARpcServer * handle,size_t threads)171 void ARpcServer_setMaxThreads(ARpcServer* handle, size_t threads) {
172     handleToStrongPointer<RpcServer>(handle)->setMaxThreads(threads);
173 }
174 
ARpcServer_start(ARpcServer * handle)175 void ARpcServer_start(ARpcServer* handle) {
176     handleToStrongPointer<RpcServer>(handle)->start();
177 }
178 
ARpcServer_join(ARpcServer * handle)179 void ARpcServer_join(ARpcServer* handle) {
180     handleToStrongPointer<RpcServer>(handle)->join();
181 }
182 
ARpcServer_shutdown(ARpcServer * handle)183 bool ARpcServer_shutdown(ARpcServer* handle) {
184     return handleToStrongPointer<RpcServer>(handle)->shutdown();
185 }
186 
ARpcServer_free(ARpcServer * handle)187 void ARpcServer_free(ARpcServer* handle) {
188     // Ignore the result of ARpcServer_shutdown - either it had been called
189     // earlier, or the RpcServer destructor will panic.
190     (void)ARpcServer_shutdown(handle);
191     freeObjectHandle<RpcServer>(handle);
192 }
193 
ARpcSession_new()194 ARpcSession* ARpcSession_new() {
195     auto session = RpcSession::make();
196     return createObjectHandle<ARpcSession>(session);
197 }
198 
ARpcSession_free(ARpcSession * handle)199 void ARpcSession_free(ARpcSession* handle) {
200     freeObjectHandle<RpcSession>(handle);
201 }
202 
203 #ifndef __TRUSTY__
ARpcSession_setupVsockClient(ARpcSession * handle,unsigned int cid,unsigned int port)204 AIBinder* ARpcSession_setupVsockClient(ARpcSession* handle, unsigned int cid, unsigned int port) {
205     auto session = handleToStrongPointer<RpcSession>(handle);
206     if (status_t status = session->setupVsockClient(cid, port); status != OK) {
207         ALOGE("Failed to set up vsock client with CID %u and port %u error: %s", cid, port,
208               statusToString(status).c_str());
209         return nullptr;
210     }
211     return AIBinder_fromPlatformBinder(session->getRootObject());
212 }
213 
ARpcSession_setupUnixDomainClient(ARpcSession * handle,const char * name)214 AIBinder* ARpcSession_setupUnixDomainClient(ARpcSession* handle, const char* name) {
215     std::string pathname(name);
216     pathname = ANDROID_SOCKET_DIR "/" + pathname;
217     auto session = handleToStrongPointer<RpcSession>(handle);
218     if (status_t status = session->setupUnixDomainClient(pathname.c_str()); status != OK) {
219         ALOGE("Failed to set up Unix Domain RPC client with path: %s error: %s", pathname.c_str(),
220               statusToString(status).c_str());
221         return nullptr;
222     }
223     return AIBinder_fromPlatformBinder(session->getRootObject());
224 }
225 
ARpcSession_setupUnixDomainBootstrapClient(ARpcSession * handle,int bootstrapFd)226 AIBinder* ARpcSession_setupUnixDomainBootstrapClient(ARpcSession* handle, int bootstrapFd) {
227     auto session = handleToStrongPointer<RpcSession>(handle);
228     auto fd = unique_fd(dup(bootstrapFd));
229     if (!fd.ok()) {
230         ALOGE("Invalid bootstrap fd %d", bootstrapFd);
231         return nullptr;
232     }
233     if (status_t status = session->setupUnixDomainSocketBootstrapClient(std::move(fd));
234         status != OK) {
235         ALOGE("Failed to set up Unix Domain RPC client with bootstrap fd: %d error: %s",
236               bootstrapFd, statusToString(status).c_str());
237         return nullptr;
238     }
239     return AIBinder_fromPlatformBinder(session->getRootObject());
240 }
241 
ARpcSession_setupInet(ARpcSession * handle,const char * address,unsigned int port)242 AIBinder* ARpcSession_setupInet(ARpcSession* handle, const char* address, unsigned int port) {
243     auto session = handleToStrongPointer<RpcSession>(handle);
244     if (status_t status = session->setupInetClient(address, port); status != OK) {
245         ALOGE("Failed to set up inet RPC client with address %s and port %u error: %s", address,
246               port, statusToString(status).c_str());
247         return nullptr;
248     }
249     return AIBinder_fromPlatformBinder(session->getRootObject());
250 }
251 #endif // __TRUSTY__
252 
ARpcSession_setupPreconnectedClient(ARpcSession * handle,int (* requestFd)(void * param),void * param)253 AIBinder* ARpcSession_setupPreconnectedClient(ARpcSession* handle, int (*requestFd)(void* param),
254                                               void* param) {
255     auto session = handleToStrongPointer<RpcSession>(handle);
256     auto request = [=] { return unique_fd{requestFd(param)}; };
257     if (status_t status = session->setupPreconnectedClient(unique_fd{}, request); status != OK) {
258         ALOGE("Failed to set up preconnected client. error: %s", statusToString(status).c_str());
259         return nullptr;
260     }
261     return AIBinder_fromPlatformBinder(session->getRootObject());
262 }
263 
ARpcSession_setFileDescriptorTransportMode(ARpcSession * handle,ARpcSession_FileDescriptorTransportMode mode)264 void ARpcSession_setFileDescriptorTransportMode(ARpcSession* handle,
265                                                 ARpcSession_FileDescriptorTransportMode mode) {
266     auto session = handleToStrongPointer<RpcSession>(handle);
267     session->setFileDescriptorTransportMode(toTransportMode(mode));
268 }
269 
ARpcSession_setMaxIncomingThreads(ARpcSession * handle,size_t threads)270 void ARpcSession_setMaxIncomingThreads(ARpcSession* handle, size_t threads) {
271     auto session = handleToStrongPointer<RpcSession>(handle);
272     session->setMaxIncomingThreads(threads);
273 }
274 
ARpcSession_setMaxOutgoingConnections(ARpcSession * handle,size_t connections)275 void ARpcSession_setMaxOutgoingConnections(ARpcSession* handle, size_t connections) {
276     auto session = handleToStrongPointer<RpcSession>(handle);
277     session->setMaxOutgoingConnections(connections);
278 }
279 }
280