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