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 #include "chre/util/pigweed/rpc_helper.h"
18
19 #include <cinttypes>
20
21 #include "chre/util/nanoapp/log.h"
22
23 #ifndef LOG_TAG
24 #define LOG_TAG "[RpcHelper]"
25 #endif // LOG_TAG
26
27 namespace chre {
28
29 namespace {
isRpcChannelIdHost(uint32_t id)30 bool inline isRpcChannelIdHost(uint32_t id) {
31 return id >> 16 == 1;
32 }
33
isRpcChannelIdNanoapp(uint32_t id)34 bool inline isRpcChannelIdNanoapp(uint32_t id) {
35 return id >> 16 == 0;
36 }
37 } // namespace
38
rpcEndpointsMatch(uint32_t expectedId,uint32_t actualId)39 bool rpcEndpointsMatch(uint32_t expectedId, uint32_t actualId) {
40 if ((expectedId & kRpcClientIdMask) != (actualId & kRpcClientIdMask)) {
41 LOGE("Invalid endpoint 0x%04" PRIx32 ", expected 0x%04" PRIx32, actualId,
42 expectedId);
43 return false;
44 }
45
46 return true;
47 }
48
validateHostChannelId(const chreMessageFromHostData * msg,uint32_t channelId)49 bool validateHostChannelId(const chreMessageFromHostData *msg,
50 uint32_t channelId) {
51 struct chreHostEndpointInfo info {};
52
53 if (!isRpcChannelIdHost(channelId) ||
54 !chreGetHostEndpointInfo(msg->hostEndpoint, &info)) {
55 LOGE("Invalid channelId 0x%" PRIx32 "for host endpoint %" PRIu16, channelId,
56 msg->hostEndpoint);
57 return false;
58 }
59
60 return rpcEndpointsMatch(channelId, static_cast<uint32_t>(msg->hostEndpoint));
61 }
62
validateNanoappChannelId(uint32_t nappId,uint32_t channelId)63 bool validateNanoappChannelId(uint32_t nappId, uint32_t channelId) {
64 if (nappId > kRpcNanoappMaxId) {
65 LOGE("Invalid nanoapp Id 0x%08" PRIx32, nappId);
66 return false;
67 }
68
69 if (!isRpcChannelIdNanoapp(channelId)) {
70 LOGE("Invalid channelId for a nanoapp 0x%08" PRIx32, channelId);
71 return false;
72 }
73
74 return rpcEndpointsMatch(channelId, nappId);
75 }
76
77 } // namespace chre