xref: /aosp_15_r20/frameworks/native/libs/binder/trusty/RpcServerTrusty.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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     if (channelContext == nullptr) {
155         LOG_RPC_DETAIL("bad state: message received on uninitialized channel");
156         return ERR_BAD_STATE;
157     }
158 
159     auto& session = channelContext->session;
160     auto& connection = channelContext->connection;
161     status_t status =
162             session->state()->drainCommands(connection, session, RpcState::CommandType::ANY);
163     if (status != OK) {
164         LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
165                        statusToString(status).c_str());
166     }
167 
168     return NO_ERROR;
169 }
170 
handleDisconnect(const tipc_port *,handle_t,void * ctx)171 void RpcServerTrusty::handleDisconnect(const tipc_port* /*port*/, handle_t /*chan*/, void* ctx) {
172     return handleDisconnectInternal(ctx);
173 }
174 
handleDisconnectInternal(void * ctx)175 void RpcServerTrusty::handleDisconnectInternal(void* ctx) {
176     auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
177     if (channelContext == nullptr) {
178         // Connections marked "incoming" (outgoing from the server's side)
179         // do not have a valid channel context because joinFn does not get
180         // called for them. We ignore them here.
181         return;
182     }
183 
184     auto& session = channelContext->session;
185     (void)session->shutdownAndWait(false);
186 }
187 
handleChannelCleanup(void * ctx)188 void RpcServerTrusty::handleChannelCleanup(void* ctx) {
189     auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
190     if (channelContext == nullptr) {
191         return;
192     }
193 
194     auto& session = channelContext->session;
195     auto& connection = channelContext->connection;
196     LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
197                         "bad state: connection object guaranteed to be in list");
198 
199     delete channelContext;
200 }
201 
202 } // namespace android
203