summaryrefslogtreecommitdiff
path: root/libs/binder/libbinder_rpc_unstable.cpp
blob: cb44c58c2cc3c0b36fa5ca5311813cfb80ce1d52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <binder_rpc_unstable.hpp>

#include <android/binder_libbinder.h>
#include <binder/RpcServer.h>
#include <binder/RpcSession.h>
#include <binder/unique_fd.h>

#ifndef __TRUSTY__
#include <cutils/sockets.h>
#endif

#ifdef __linux__
#include <linux/vm_sockets.h>
#endif // __linux__

using android::OK;
using android::RpcServer;
using android::RpcSession;
using android::sp;
using android::status_t;
using android::statusToString;
using android::binder::unique_fd;

// Opaque handle for RpcServer.
struct ARpcServer {};

// Opaque handle for RpcSession.
struct ARpcSession {};

template <typename A, typename T>
static A* createObjectHandle(sp<T>& server) {
    auto ref = server.get();
    ref->incStrong(ref);
    return reinterpret_cast<A*>(ref);
}

template <typename T, typename A>
static void freeObjectHandle(A* handle) {
    LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
    auto ref = reinterpret_cast<T*>(handle);
    ref->decStrong(ref);
}

template <typename T, typename A>
static sp<T> handleToStrongPointer(A* handle) {
    LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
    auto ref = reinterpret_cast<T*>(handle);
    return sp<T>::fromExisting(ref);
}

RpcSession::FileDescriptorTransportMode toTransportMode(
        ARpcSession_FileDescriptorTransportMode mode) {
    switch (mode) {
        case ARpcSession_FileDescriptorTransportMode::None:
            return RpcSession::FileDescriptorTransportMode::NONE;
        case ARpcSession_FileDescriptorTransportMode::Unix:
            return RpcSession::FileDescriptorTransportMode::UNIX;
        case ARpcSession_FileDescriptorTransportMode::Trusty:
            return RpcSession::FileDescriptorTransportMode::TRUSTY;
        default:
            return RpcSession::FileDescriptorTransportMode::NONE;
    }
}

extern "C" {

#ifndef __TRUSTY__
ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int cid, unsigned int port) {
    auto server = RpcServer::make();

    unsigned int bindCid = VMADDR_CID_ANY; // bind to the remote interface
    if (cid == VMADDR_CID_LOCAL) {
        bindCid = VMADDR_CID_LOCAL; // bind to the local interface
        cid = VMADDR_CID_ANY;       // no need for a connection filter
    }

    if (status_t status = server->setupVsockServer(bindCid, port); status != OK) {
        ALOGE("Failed to set up vsock server with port %u error: %s", port,
              statusToString(status).c_str());
        return nullptr;
    }
    if (cid != VMADDR_CID_ANY) {
        server->setConnectionFilter([=](const void* addr, size_t addrlen) {
            LOG_ALWAYS_FATAL_IF(addrlen < sizeof(sockaddr_vm), "sockaddr is truncated");
            const sockaddr_vm* vaddr = reinterpret_cast<const sockaddr_vm*>(addr);
            LOG_ALWAYS_FATAL_IF(vaddr->svm_family != AF_VSOCK, "address is not a vsock");
            if (cid != vaddr->svm_cid) {
                ALOGE("Rejected vsock connection from CID %u", vaddr->svm_cid);
                return false;
            }
            return true;
        });
    }
    server->setRootObject(AIBinder_toPlatformBinder(service));
    return createObjectHandle<ARpcServer>(server);
}

ARpcServer* ARpcServer_newBoundSocket(AIBinder* service, int socketFd) {
    auto server = RpcServer::make();
    auto fd = unique_fd(socketFd);
    if (!fd.ok()) {
        ALOGE("Invalid socket fd %d", socketFd);
        return nullptr;
    }
    if (status_t status = server->setupRawSocketServer(std::move(fd)); status != OK) {
        ALOGE("Failed to set up RPC server with fd %d error: %s", socketFd,
              statusToString(status).c_str());
        return nullptr;
    }
    server->setRootObject(AIBinder_toPlatformBinder(service));
    return createObjectHandle<ARpcServer>(server);
}

ARpcServer* ARpcServer_newUnixDomainBootstrap(AIBinder* service, int bootstrapFd) {
    auto server = RpcServer::make();
    auto fd = unique_fd(bootstrapFd);
    if (!fd.ok()) {
        ALOGE("Invalid bootstrap fd %d", bootstrapFd);
        return nullptr;
    }
    if (status_t status = server->setupUnixDomainSocketBootstrapServer(std::move(fd));
        status != OK) {
        ALOGE("Failed to set up Unix Domain RPC server with bootstrap fd %d error: %s", bootstrapFd,
              statusToString(status).c_str());
        return nullptr;
    }
    server->setRootObject(AIBinder_toPlatformBinder(service));
    return createObjectHandle<ARpcServer>(server);
}

ARpcServer* ARpcServer_newInet(AIBinder* service, const char* address, unsigned int port) {
    auto server = RpcServer::make();
    if (status_t status = server->setupInetServer(address, port, nullptr); status != OK) {
        ALOGE("Failed to set up inet RPC server with address %s and port %u error: %s", address,
              port, statusToString(status).c_str());
        return nullptr;
    }
    server->setRootObject(AIBinder_toPlatformBinder(service));
    return createObjectHandle<ARpcServer>(server);
}
#endif // __TRUSTY__

void ARpcServer_setSupportedFileDescriptorTransportModes(
        ARpcServer* handle, const ARpcSession_FileDescriptorTransportMode modes[],
        size_t modes_len) {
    auto server = handleToStrongPointer<RpcServer>(handle);
    std::vector<RpcSession::FileDescriptorTransportMode> modevec;
    for (size_t i = 0; i < modes_len; i++) {
        modevec.push_back(toTransportMode(modes[i]));
    }
    server->setSupportedFileDescriptorTransportModes(modevec);
}

void ARpcServer_start(ARpcServer* handle) {
    handleToStrongPointer<RpcServer>(handle)->start();
}

void ARpcServer_join(ARpcServer* handle) {
    handleToStrongPointer<RpcServer>(handle)->join();
}

bool ARpcServer_shutdown(ARpcServer* handle) {
    return handleToStrongPointer<RpcServer>(handle)->shutdown();
}

void ARpcServer_free(ARpcServer* handle) {
    // Ignore the result of ARpcServer_shutdown - either it had been called
    // earlier, or the RpcServer destructor will panic.
    (void)ARpcServer_shutdown(handle);
    freeObjectHandle<RpcServer>(handle);
}

ARpcSession* ARpcSession_new() {
    auto session = RpcSession::make();
    return createObjectHandle<ARpcSession>(session);
}

void ARpcSession_free(ARpcSession* handle) {
    freeObjectHandle<RpcSession>(handle);
}

#ifndef __TRUSTY__
AIBinder* ARpcSession_setupVsockClient(ARpcSession* handle, unsigned int cid, unsigned int port) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    if (status_t status = session->setupVsockClient(cid, port); status != OK) {
        ALOGE("Failed to set up vsock client with CID %u and port %u error: %s", cid, port,
              statusToString(status).c_str());
        return nullptr;
    }
    return AIBinder_fromPlatformBinder(session->getRootObject());
}

AIBinder* ARpcSession_setupUnixDomainClient(ARpcSession* handle, const char* name) {
    std::string pathname(name);
    pathname = ANDROID_SOCKET_DIR "/" + pathname;
    auto session = handleToStrongPointer<RpcSession>(handle);
    if (status_t status = session->setupUnixDomainClient(pathname.c_str()); status != OK) {
        ALOGE("Failed to set up Unix Domain RPC client with path: %s error: %s", pathname.c_str(),
              statusToString(status).c_str());
        return nullptr;
    }
    return AIBinder_fromPlatformBinder(session->getRootObject());
}

AIBinder* ARpcSession_setupUnixDomainBootstrapClient(ARpcSession* handle, int bootstrapFd) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    auto fd = unique_fd(dup(bootstrapFd));
    if (!fd.ok()) {
        ALOGE("Invalid bootstrap fd %d", bootstrapFd);
        return nullptr;
    }
    if (status_t status = session->setupUnixDomainSocketBootstrapClient(std::move(fd));
        status != OK) {
        ALOGE("Failed to set up Unix Domain RPC client with bootstrap fd: %d error: %s",
              bootstrapFd, statusToString(status).c_str());
        return nullptr;
    }
    return AIBinder_fromPlatformBinder(session->getRootObject());
}

AIBinder* ARpcSession_setupInet(ARpcSession* handle, const char* address, unsigned int port) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    if (status_t status = session->setupInetClient(address, port); status != OK) {
        ALOGE("Failed to set up inet RPC client with address %s and port %u error: %s", address,
              port, statusToString(status).c_str());
        return nullptr;
    }
    return AIBinder_fromPlatformBinder(session->getRootObject());
}
#endif // __TRUSTY__

AIBinder* ARpcSession_setupPreconnectedClient(ARpcSession* handle, int (*requestFd)(void* param),
                                              void* param) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    auto request = [=] { return unique_fd{requestFd(param)}; };
    if (status_t status = session->setupPreconnectedClient(unique_fd{}, request); status != OK) {
        ALOGE("Failed to set up preconnected client. error: %s", statusToString(status).c_str());
        return nullptr;
    }
    return AIBinder_fromPlatformBinder(session->getRootObject());
}

void ARpcSession_setFileDescriptorTransportMode(ARpcSession* handle,
                                                ARpcSession_FileDescriptorTransportMode mode) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    session->setFileDescriptorTransportMode(toTransportMode(mode));
}

void ARpcSession_setMaxIncomingThreads(ARpcSession* handle, size_t threads) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    session->setMaxIncomingThreads(threads);
}

void ARpcSession_setMaxOutgoingConnections(ARpcSession* handle, size_t connections) {
    auto session = handleToStrongPointer<RpcSession>(handle);
    session->setMaxOutgoingConnections(connections);
}
}