1 /*
2  * Copyright (C) 2022 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 "RpcServerTrusty"
18 
19 #include <binder/Parcel.h>
20 #include <binder/RpcServer.h>
21 #include <binder/RpcServerTrusty.h>
22 #include <binder/RpcThreads.h>
23 #include <binder/RpcTransportTipcTrusty.h>
24 #include <log/log.h>
25 
26 #include "../FdTrigger.h"
27 #include "../RpcState.h"
28 #include "TrustyStatus.h"
29 
30 using android::binder::unique_fd;
31 
32 namespace android {
33 
make(tipc_hset * handleSet,std::string && portName,std::shared_ptr<const PortAcl> && portAcl,size_t msgMaxSize,std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)34 sp<RpcServerTrusty> RpcServerTrusty::make(
35         tipc_hset* handleSet, std::string&& portName, std::shared_ptr<const PortAcl>&& portAcl,
36         size_t msgMaxSize, std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
37     // Default is without TLS.
38     if (rpcTransportCtxFactory == nullptr)
39         rpcTransportCtxFactory = RpcTransportCtxFactoryTipcTrusty::make();
40     auto ctx = rpcTransportCtxFactory->newServerCtx();
41     if (ctx == nullptr) {
42         ALOGE("Failed to create RpcServerTrusty: can't create server context");
43         return nullptr;
44     }
45 
46     auto srv = sp<RpcServerTrusty>::make(std::move(ctx), std::move(portName), std::move(portAcl),
47                                          msgMaxSize);
48     if (srv == nullptr) {
49         ALOGE("Failed to create RpcServerTrusty: can't create server object");
50         return nullptr;
51     }
52 
53     int rc = tipc_add_service(handleSet, &srv->mTipcPort, 1, 0, &kTipcOps);
54     if (rc != NO_ERROR) {
55         ALOGE("Failed to create RpcServerTrusty: can't add service: %d", rc);
56         return nullptr;
57     }
58     return srv;
59 }
60 
RpcServerTrusty(std::unique_ptr<RpcTransportCtx> ctx,std::string && portName,std::shared_ptr<const PortAcl> && portAcl,size_t msgMaxSize)61 RpcServerTrusty::RpcServerTrusty(std::unique_ptr<RpcTransportCtx> ctx, std::string&& portName,
62                                  std::shared_ptr<const PortAcl>&& portAcl, size_t msgMaxSize)
63       : mRpcServer(makeRpcServer(std::move(ctx))),
64         mPortName(std::move(portName)),
65         mPortAcl(std::move(portAcl)) {
66     mTipcPort.name = mPortName.c_str();
67     mTipcPort.msg_max_size = msgMaxSize;
68     mTipcPort.msg_queue_len = 6; // Three each way
69     mTipcPort.priv = this;
70 
71     if (mPortAcl) {
72         // Initialize the array of pointers to uuids.
73         // The pointers in mUuidPtrs should stay valid across moves of
74         // RpcServerTrusty (the addresses of a std::vector's elements
75         // shouldn't change when the vector is moved), but would be invalidated
76         // by a copy which is why we disable the copy constructor and assignment
77         // operator for RpcServerTrusty.
78         auto numUuids = mPortAcl->uuids.size();
79         mUuidPtrs.resize(numUuids);
80         for (size_t i = 0; i < numUuids; i++) {
81             mUuidPtrs[i] = &mPortAcl->uuids[i];
82         }
83 
84         // Copy the contents of portAcl into the tipc_port_acl structure that we
85         // pass to tipc_add_service
86         mTipcPortAcl.flags = mPortAcl->flags;
87         mTipcPortAcl.uuid_num = numUuids;
88         mTipcPortAcl.uuids = mUuidPtrs.data();
89         mTipcPortAcl.extra_data = mPortAcl->extraData;
90 
91         mTipcPort.acl = &mTipcPortAcl;
92     } else {
93         mTipcPort.acl = nullptr;
94     }
95 }
96 
handleConnect(const tipc_port * port,handle_t chan,const uuid * peer,void ** ctx_p)97 int RpcServerTrusty::handleConnect(const tipc_port* port, handle_t chan, const uuid* peer,
98                                    void** ctx_p) {
99     auto* server = reinterpret_cast<RpcServerTrusty*>(const_cast<void*>(port->priv));
100     return handleConnectInternal(server->mRpcServer.get(), chan, peer, ctx_p);
101 }
102 
handleConnectInternal(RpcServer * rpcServer,handle_t chan,const uuid * peer,void ** ctx_p)103 int RpcServerTrusty::handleConnectInternal(RpcServer* rpcServer, handle_t chan, const uuid* peer,
104                                            void** ctx_p) {
105     rpcServer->mShutdownTrigger = FdTrigger::make();
106     rpcServer->mConnectingThreads[rpc_this_thread::get_id()] = RpcMaybeThread();
107 
108     int rc = NO_ERROR;
109     auto joinFn = [&](sp<RpcSession>&& session, RpcSession::PreJoinSetupResult&& result) {
110         if (result.status != OK) {
111             rc = statusToTrusty(result.status);
112             return;
113         }
114 
115         /* Save the session and connection for the other callbacks */
116         auto* channelContext = new (std::nothrow) ChannelContext;
117         if (channelContext == nullptr) {
118             rc = ERR_NO_MEMORY;
119             return;
120         }
121 
122         channelContext->session = std::move(session);
123         channelContext->connection = std::move(result.connection);
124 
125         *ctx_p = channelContext;
126     };
127 
128     // We need to duplicate the channel handle here because the tipc library
129     // owns the original handle and closes is automatically on channel cleanup.
130     // We use dup() because Trusty does not have fcntl().
131     // NOLINTNEXTLINE(android-cloexec-dup)
132     handle_t chanDup = dup(chan);
133     if (chanDup < 0) {
134         return chanDup;
135     }
136     unique_fd clientFd(chanDup);
137     android::RpcTransportFd transportFd(std::move(clientFd));
138 
139     std::array<uint8_t, RpcServer::kRpcAddressSize> addr;
140     constexpr size_t addrLen = sizeof(*peer);
141     memcpy(addr.data(), peer, addrLen);
142     RpcServer::establishConnection(sp<RpcServer>::fromExisting(rpcServer), std::move(transportFd),
143                                    addr, addrLen, joinFn);
144 
145     return rc;
146 }
147 
handleMessage(const tipc_port *,handle_t,void * ctx)148 int RpcServerTrusty::handleMessage(const tipc_port* /*port*/, handle_t /*chan*/, void* ctx) {
149     return handleMessageInternal(ctx);
150 }
151 
handleMessageInternal(void * ctx)152 int RpcServerTrusty::handleMessageInternal(void* ctx) {
153     auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
154     LOG_ALWAYS_FATAL_IF(channelContext == nullptr,
155                         "bad state: message received on uninitialized channel");
156 
157     auto& session = channelContext->session;
158     auto& connection = channelContext->connection;
159     status_t status =
160             session->state()->drainCommands(connection, session, RpcState::CommandType::ANY);
161     if (status != OK) {
162         LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
163                        statusToString(status).c_str());
164     }
165 
166     return NO_ERROR;
167 }
168 
handleDisconnect(const tipc_port *,handle_t,void * ctx)169 void RpcServerTrusty::handleDisconnect(const tipc_port* /*port*/, handle_t /*chan*/, void* ctx) {
170     return handleDisconnectInternal(ctx);
171 }
172 
handleDisconnectInternal(void * ctx)173 void RpcServerTrusty::handleDisconnectInternal(void* ctx) {
174     auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
175     if (channelContext == nullptr) {
176         // Connections marked "incoming" (outgoing from the server's side)
177         // do not have a valid channel context because joinFn does not get
178         // called for them. We ignore them here.
179         return;
180     }
181 
182     auto& session = channelContext->session;
183     (void)session->shutdownAndWait(false);
184 }
185 
handleChannelCleanup(void * ctx)186 void RpcServerTrusty::handleChannelCleanup(void* ctx) {
187     auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
188     if (channelContext == nullptr) {
189         return;
190     }
191 
192     auto& session = channelContext->session;
193     auto& connection = channelContext->connection;
194     LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
195                         "bad state: connection object guaranteed to be in list");
196 
197     delete channelContext;
198 }
199 
200 } // namespace android
201