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
16 #include "utils_common.h"
17 #include <algorithm>
18 #include <cerrno>
19 #include <cstdint>
20 #include <cstdlib>
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <limits>
24 #include <linux/reboot.h>
25 #include <string>
26 #include <sys/reboot.h>
27 #include <sys/stat.h>
28 #include <sys/syscall.h>
29 #include <unistd.h>
30 #include <vector>
31 #include "log/log.h"
32
33 namespace Updater {
34 namespace Utils {
35 constexpr int USECONDS_PER_SECONDS = 1000000; // 1s = 1000000us
36 constexpr int NANOSECS_PER_USECONDS = 1000; // 1us = 1000ns
37
PathToRealPath(const std::string & path,std::string & realPath)38 bool PathToRealPath(const std::string &path, std::string &realPath)
39 {
40 if (path.empty()) {
41 LOG(ERROR) << "path is empty!";
42 return false;
43 }
44
45 if ((path.length() >= PATH_MAX)) {
46 LOG(ERROR) << "path len is error, the len is: " << path.length();
47 return false;
48 }
49
50 char tmpPath[PATH_MAX] = {0};
51 if (realpath(path.c_str(), tmpPath) == nullptr) {
52 LOG(ERROR) << "path to realpath error " << path;
53 return false;
54 }
55
56 realPath = tmpPath;
57 return true;
58 }
59
UsSleep(int usec)60 void UsSleep(int usec)
61 {
62 auto seconds = usec / USECONDS_PER_SECONDS;
63 long nanoSeconds = static_cast<long>(usec) % USECONDS_PER_SECONDS * NANOSECS_PER_USECONDS;
64 struct timespec ts = { static_cast<time_t>(seconds), nanoSeconds };
65 while (nanosleep(&ts, &ts) < 0 && errno == EINTR) {
66 }
67 }
68
IsUpdaterMode()69 bool IsUpdaterMode()
70 {
71 struct stat st {};
72 if (stat("/bin/updater", &st) == 0 && S_ISREG(st.st_mode)) {
73 LOG(INFO) << "updater mode";
74 return true;
75 }
76 LOG(INFO) << "normal mode";
77 return false;
78 }
79 } // Utils
80 } // updater
81