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)84 ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int cid, unsigned int port) {
85     auto server = RpcServer::make();
86 
87     unsigned int bindCid = VMADDR_CID_ANY; // bind to the remote interface
88     if (cid == VMADDR_CID_LOCAL) {
89         bindCid = VMADDR_CID_LOCAL; // bind to the local interface
90         cid = VMADDR_CID_ANY;       // no need for a connection filter
91     }
92 
93     if (status_t status = server->setupVsockServer(bindCid, port); status != OK) {
94         ALOGE("Failed to set up vsock server with port %u error: %s", port,
95               statusToString(status).c_str());
96         return nullptr;
97     }
98     if (cid != VMADDR_CID_ANY) {
99         server->setConnectionFilter([=](const void* addr, size_t addrlen) {
100             LOG_ALWAYS_FATAL_IF(addrlen < sizeof(sockaddr_vm), "sockaddr is truncated");
101             const sockaddr_vm* vaddr = reinterpret_cast<const sockaddr_vm*>(addr);
102             LOG_ALWAYS_FATAL_IF(vaddr->svm_family != AF_VSOCK, "address is not a vsock");
103             if (cid != vaddr->svm_cid) {
104                 ALOGE("Rejected vsock connection from CID %u", vaddr->svm_cid);
105                 return false;
106             }
107             return true;
108         });
109     }
110     server->setRootObject(AIBinder_toPlatformBinder(service));
111     return createObjectHandle<ARpcServer>(server);
112 }
113 
ARpcServer_newBoundSocket(AIBinder * service,int socketFd)114 ARpcServer* ARpcServer_newBoundSocket(AIBinder* service, int socketFd) {
115     auto server = RpcServer::make();
116     auto fd = unique_fd(socketFd);
117     if (!fd.ok()) {
118         ALOGE("Invalid socket fd %d", socketFd);
119         return nullptr;
120     }
121     if (status_t status = server->setupRawSocketServer(std::move(fd)); status != OK) {
122         ALOGE("Failed to set up RPC server with fd %d error: %s", socketFd,
123               statusToString(status).c_str());
124         return nullptr;
125     }
126     server->setRootObject(AIBinder_toPlatformBinder(service));
127     return createObjectHandle<ARpcServer>(server);
128 }
129 
ARpcServer_newUnixDomainBootstrap(AIBinder * service,int bootstrapFd)130 ARpcServer* ARpcServer_newUnixDomainBootstrap(AIBinder* service, int bootstrapFd) {
131     auto server = RpcServer::make();
132     auto fd = unique_fd(bootstrapFd);
133     if (!fd.ok()) {
134         ALOGE("Invalid bootstrap fd %d", bootstrapFd);
135         return nullptr;
136     }
137     if (status_t status = server->setupUnixDomainSocketBootstrapServer(std::move(fd));
138         status != OK) {
139         ALOGE("Failed to set up Unix Domain RPC server with bootstrap fd %d error: %s", bootstrapFd,
140               statusToString(status).c_str());
141         return nullptr;
142     }
143     server->setRootObject(AIBinder_toPlatformBinder(service));
144     return createObjectHandle<ARpcServer>(server);
145 }
146 
ARpcServer_newInet(AIBinder * service,const char * address,unsigned int port)147 ARpcServer* ARpcServer_newInet(AIBinder* service, const char* address, unsigned int port) {
148     auto server = RpcServer::make();
149     if (status_t status = server->setupInetServer(address, port, nullptr); status != OK) {
150         ALOGE("Failed to set up inet RPC server with address %s and port %u error: %s", address,
151               port, statusToString(status).c_str());
152         return nullptr;
153     }
154     server->setRootObject(AIBinder_toPlatformBinder(service));
155     return createObjectHandle<ARpcServer>(server);
156 }
157 #endif // __TRUSTY__
158 
ARpcServer_setSupportedFileDescriptorTransportModes(ARpcServer * handle,const ARpcSession_FileDescriptorTransportMode modes[],size_t modes_len)159 void ARpcServer_setSupportedFileDescriptorTransportModes(
160         ARpcServer* handle, const ARpcSession_FileDescriptorTransportMode modes[],
161         size_t modes_len) {
162     auto server = handleToStrongPointer<RpcServer>(handle);
163     std::vector<RpcSession::FileDescriptorTransportMode> modevec;
164     for (size_t i = 0; i < modes_len; i++) {
165         modevec.push_back(toTransportMode(modes[i]));
166     }
167     server->setSupportedFileDescriptorTransportModes(modevec);
168 }
169 
ARpcServer_setMaxThreads(ARpcServer * handle,size_t threads)170 void ARpcServer_setMaxThreads(ARpcServer* handle, size_t threads) {
171     handleToStrongPointer<RpcServer>(handle)->setMaxThreads(threads);
172 }
173 
ARpcServer_start(ARpcServer * handle)174 void ARpcServer_start(ARpcServer* handle) {
175     handleToStrongPointer<RpcServer>(handle)->start();
176 }
177 
ARpcServer_join(ARpcServer * handle)178 void ARpcServer_join(ARpcServer* handle) {
179     handleToStrongPointer<RpcServer>(handle)->join();
180 }
181 
ARpcServer_shutdown(ARpcServer * handle)182 bool ARpcServer_shutdown(ARpcServer* handle) {
183     return handleToStrongPointer<RpcServer>(handle)->shutdown();
184 }
185 
ARpcServer_free(ARpcServer * handle)186 void ARpcServer_free(ARpcServer* handle) {
187     // Ignore the result of ARpcServer_shutdown - either it had been called
188     // earlier, or the RpcServer destructor will panic.
189     (void)ARpcServer_shutdown(handle);
190     freeObjectHandle<RpcServer>(handle);
191 }
192 
ARpcSession_new()193 ARpcSession* ARpcSession_new() {
194     auto session = RpcSession::make();
195     return createObjectHandle<ARpcSession>(session);
196 }
197 
ARpcSession_free(ARpcSession * handle)198 void ARpcSession_free(ARpcSession* handle) {
199     freeObjectHandle<RpcSession>(handle);
200 }
201 
202 #ifndef __TRUSTY__
ARpcSession_setupVsockClient(ARpcSession * handle,unsigned int cid,unsigned int port)203 AIBinder* ARpcSession_setupVsockClient(ARpcSession* handle, unsigned int cid, unsigned int port) {
204     auto session = handleToStrongPointer<RpcSession>(handle);
205     if (status_t status = session->setupVsockClient(cid, port); status != OK) {
206         ALOGE("Failed to set up vsock client with CID %u and port %u error: %s", cid, port,
207               statusToString(status).c_str());
208         return nullptr;
209     }
210     return AIBinder_fromPlatformBinder(session->getRootObject());
211 }
212 
ARpcSession_setupUnixDomainClient(ARpcSession * handle,const char * name)213 AIBinder* ARpcSession_setupUnixDomainClient(ARpcSession* handle, const char* name) {
214     std::string pathname(name);
215     pathname = ANDROID_SOCKET_DIR "/" + pathname;
216     auto session = handleToStrongPointer<RpcSession>(handle);
217     if (status_t status = session->setupUnixDomainClient(pathname.c_str()); status != OK) {
218         ALOGE("Failed to set up Unix Domain RPC client with path: %s error: %s", pathname.c_str(),
219               statusToString(status).c_str());
220         return nullptr;
221     }
222     return AIBinder_fromPlatformBinder(session->getRootObject());
223 }
224 
ARpcSession_setupUnixDomainBootstrapClient(ARpcSession * handle,int bootstrapFd)225 AIBinder* ARpcSession_setupUnixDomainBootstrapClient(ARpcSession* handle, int bootstrapFd) {
226     auto session = handleToStrongPointer<RpcSession>(handle);
227     auto fd = unique_fd(dup(bootstrapFd));
228     if (!fd.ok()) {
229         ALOGE("Invalid bootstrap fd %d", bootstrapFd);
230         return nullptr;
231     }
232     if (status_t status = session->setupUnixDomainSocketBootstrapClient(std::move(fd));
233         status != OK) {
234         ALOGE("Failed to set up Unix Domain RPC client with bootstrap fd: %d error: %s",
235               bootstrapFd, statusToString(status).c_str());
236         return nullptr;
237     }
238     return AIBinder_fromPlatformBinder(session->getRootObject());
239 }
240 
ARpcSession_setupInet(ARpcSession * handle,const char * address,unsigned int port)241 AIBinder* ARpcSession_setupInet(ARpcSession* handle, const char* address, unsigned int port) {
242     auto session = handleToStrongPointer<RpcSession>(handle);
243     if (status_t status = session->setupInetClient(address, port); status != OK) {
244         ALOGE("Failed to set up inet RPC client with address %s and port %u error: %s", address,
245               port, statusToString(status).c_str());
246         return nullptr;
247     }
248     return AIBinder_fromPlatformBinder(session->getRootObject());
249 }
250 #endif // __TRUSTY__
251 
ARpcSession_setupPreconnectedClient(ARpcSession * handle,int (* requestFd)(void * param),void * param)252 AIBinder* ARpcSession_setupPreconnectedClient(ARpcSession* handle, int (*requestFd)(void* param),
253                                               void* param) {
254     auto session = handleToStrongPointer<RpcSession>(handle);
255     auto request = [=] { return unique_fd{requestFd(param)}; };
256     if (status_t status = session->setupPreconnectedClient(unique_fd{}, request); status != OK) {
257         ALOGE("Failed to set up preconnected client. error: %s", statusToString(status).c_str());
258         return nullptr;
259     }
260     return AIBinder_fromPlatformBinder(session->getRootObject());
261 }
262 
ARpcSession_setFileDescriptorTransportMode(ARpcSession * handle,ARpcSession_FileDescriptorTransportMode mode)263 void ARpcSession_setFileDescriptorTransportMode(ARpcSession* handle,
264                                                 ARpcSession_FileDescriptorTransportMode mode) {
265     auto session = handleToStrongPointer<RpcSession>(handle);
266     session->setFileDescriptorTransportMode(toTransportMode(mode));
267 }
268 
ARpcSession_setMaxIncomingThreads(ARpcSession * handle,size_t threads)269 void ARpcSession_setMaxIncomingThreads(ARpcSession* handle, size_t threads) {
270     auto session = handleToStrongPointer<RpcSession>(handle);
271     session->setMaxIncomingThreads(threads);
272 }
273 
ARpcSession_setMaxOutgoingConnections(ARpcSession * handle,size_t connections)274 void ARpcSession_setMaxOutgoingConnections(ARpcSession* handle, size_t connections) {
275     auto session = handleToStrongPointer<RpcSession>(handle);
276     session->setMaxOutgoingConnections(connections);
277 }
278 }
279