1 /*
2 * Copyright (c) 2023 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
16 #include "time_file_utils.h"
17
18 #include <fcntl.h>
19 #include <sys/stat.h>
20
21 #include "accesstoken_kit.h"
22 #include "ipc_skeleton.h"
23 #include "securec.h"
24 #include "time_hilog.h"
25
26 constexpr int CMDLINE_PATH_LEN = 32;
27 constexpr int CMDLINE_LEN = 128;
28
29 namespace OHOS {
30 namespace MiscServices {
31 using AccessTokenKit = OHOS::Security::AccessToken::AccessTokenKit;
32 using HapTokenInfo = OHOS::Security::AccessToken::HapTokenInfo;
33 using TypeATokenTypeEnum = OHOS::Security::AccessToken::TypeATokenTypeEnum;
IsExistFile(const std::string & file)34 bool TimeFileUtils::IsExistFile(const std::string &file)
35 {
36 if (file.empty()) {
37 return false;
38 }
39
40 struct stat buf = {};
41 if (stat(file.c_str(), &buf) != 0) {
42 return false;
43 }
44 return S_ISREG(buf.st_mode);
45 }
46
GetBundleNameByTokenID(uint32_t tokenID)47 std::string TimeFileUtils::GetBundleNameByTokenID(uint32_t tokenID)
48 {
49 auto tokenType = AccessTokenKit::GetTokenTypeFlag(tokenID);
50 if (tokenType != TypeATokenTypeEnum::TOKEN_HAP) {
51 TIME_HILOGE(TIME_MODULE_SERVICE, "not hap token");
52 return "";
53 }
54 HapTokenInfo hapTokenInfo;
55 int result = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfo);
56 if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) {
57 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to get hap token info, result = %{public}d", result);
58 return "";
59 }
60 return hapTokenInfo.bundleName;
61 }
62
GetNameByPid(uint32_t pid)63 std::string TimeFileUtils::GetNameByPid(uint32_t pid)
64 {
65 char path[CMDLINE_PATH_LEN] = { 0 };
66 if (snprintf_s(path, CMDLINE_PATH_LEN, CMDLINE_PATH_LEN - 1, "/proc/%u/cmdline", pid) <= 0) {
67 return "";
68 }
69 char cmdline[CMDLINE_LEN] = { 0 };
70 int i = 0;
71 FILE *fp = fopen(path, "r");
72 if (fp == nullptr) {
73 return "";
74 }
75 while (i < (CMDLINE_LEN - 1)) {
76 char c = static_cast<char>(fgetc(fp));
77 // 0. don't need args of cmdline
78 // 1. ignore unvisible character
79 if (!isgraph(c)) {
80 break;
81 }
82 cmdline[i] = c;
83 i++;
84 }
85 (void)fclose(fp);
86 return cmdline;
87 }
88 } // namespace MiscServices
89 } // namespace OHOS