1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #define LOG_TAG "UdmfUtils"
16
17 #include "udmf_utils.h"
18 #include <random>
19 #include <sstream>
20 #include "accesstoken_kit.h"
21 #include "ipc_skeleton.h"
22 #include "logger.h"
23
24 namespace OHOS {
25 namespace UDMF {
26 namespace UTILS {
27 static constexpr int ID_LEN = 32;
28 static constexpr int MINIMUM = 48;
29 static constexpr int MAXIMUM = 121;
30 constexpr char SPECIAL = '^';
31
Random(int32_t len,int32_t minimum,int32_t maximum)32 std::vector<uint8_t> Random(int32_t len, int32_t minimum, int32_t maximum)
33 {
34 std::random_device randomDevice;
35 std::uniform_int_distribution<int> distribution(minimum, maximum);
36 std::vector<uint8_t> key(len);
37 for (int32_t i = 0; i < len; i++) {
38 key[i] = static_cast<uint8_t>(distribution(randomDevice));
39 }
40 return key;
41 }
42
GenerateId()43 std::string GenerateId()
44 {
45 std::vector<uint8_t> randomDevices = Random(ID_LEN, MINIMUM, MAXIMUM);
46 std::stringstream idStr;
47 for (auto &randomDevice : randomDevices) {
48 auto asc = randomDevice;
49 asc = asc >= SPECIAL ? asc + 1 : asc;
50 idStr << static_cast<uint8_t>(asc);
51 }
52 return idStr.str();
53 }
54
IsTokenNative()55 bool IsTokenNative()
56 {
57 uint32_t tokenId = IPCSkeleton::GetSelfTokenID();
58 if (tokenId == 0) {
59 return false;
60 }
61 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
62 return tokenType == Security::AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE;
63 }
64
IsNativeCallingToken()65 bool IsNativeCallingToken()
66 {
67 uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
68 if (tokenId == 0) {
69 return false;
70 }
71 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
72 return tokenType == Security::AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE;
73 }
74
GetSequenceKey(const std::string & udKey)75 std::string GetSequenceKey(const std::string &udKey)
76 {
77 auto pos = udKey.rfind('/');
78 if (pos == std::string::npos || pos + 1 >= udKey.length()) {
79 LOG_ERROR(UDMF_FRAMEWORK, "Error udKey:%{public}s", udKey.c_str());
80 return "";
81 }
82 return udKey.substr(pos + 1);
83 }
84
85 } // namespace UTILS
86 } // namespace UDMF
87 } // namespace OHOS