1 /*
2  * Copyright (c) 2021 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.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 "fs_manager/mount.h"
32 #include "init_reboot.h"
33 #include "log/log.h"
34 #include "misc_info/misc_info.h"
35 #ifdef WITH_SELINUX
36 #include <policycoreutils.h>
37 #include "selinux/selinux.h"
38 #endif
39 #include "package/pkg_manager.h"
40 #include "parameter.h"
41 #include "securec.h"
42 #include "updater/updater_const.h"
43 #include "scope_guard.h"
44 
45 namespace Updater {
46 using namespace Hpackage;
47 
48 namespace Utils {
49 constexpr uint8_t SHIFT_RIGHT_FOUR_BITS = 4;
50 constexpr int MAX_TIME_SIZE = 20;
51 constexpr size_t PARAM_SIZE = 32;
52 constexpr const char *PREFIX_PARTITION_NODE = "/dev/block/by-name/";
53 constexpr mode_t DEFAULT_DIR_MODE = 0775;
54 
55 namespace {
UpdateInfoInMisc(const std::string headInfo,const std::optional<int> message,bool isRemove)56 void UpdateInfoInMisc(const std::string headInfo, const std::optional<int> message, bool isRemove)
57 {
58     if (headInfo.empty()) {
59         return;
60     }
61     std::vector<std::string> args = Utils::ParseParams(0, nullptr);
62     struct UpdateMessage msg {};
63     if (!ReadUpdaterMiscMsg(msg)) {
64         LOG(ERROR) << "SetMessageToMisc read misc failed";
65         return;
66     }
67 
68     (void)memset_s(msg.update, sizeof(msg.update), 0, sizeof(msg.update));
69     for (const auto& arg : args) {
70         if (arg.find(headInfo) == std::string::npos) {
71             if (strncat_s(msg.update, sizeof(msg.update), arg.c_str(), strlen(arg.c_str()) + 1) != EOK) {
72                 LOG(ERROR) << "SetMessageToMisc strncat_s failed";
73                 return;
74             }
75             if (strncat_s(msg.update, sizeof(msg.update), "\n", strlen("\n") + 1) != EOK) {
76                 LOG(ERROR) << "SetMessageToMisc strncat_s failed";
77                 return;
78             }
79         }
80     }
81     char buffer[128] {}; // 128 : set headInfo size
82     if (isRemove) {
83         LOG(INFO) << "remove --" << headInfo << " from misc";
84     } else if (!message.has_value()) {
85         if (snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, "--%s", headInfo.c_str()) == -1) {
86             LOG(ERROR) << "SetMessageToMisc snprintf_s failed";
87             return;
88         }
89     } else {
90         if (snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, "--%s=%d",
91             headInfo.c_str(), message.value()) == -1) {
92             LOG(ERROR) << "SetMessageToMisc snprintf_s failed";
93             return;
94         }
95     }
96     if (strncat_s(msg.update, sizeof(msg.update), buffer, strlen(buffer) + 1) != EOK) {
97         LOG(ERROR) << "SetMessageToMisc strncat_s failed";
98         return;
99     }
100     if (WriteUpdaterMiscMsg(msg) != true) {
101         LOG(ERROR) << "Write command to misc failed.";
102     }
103 }
104 } // namespace
105 
SaveLogs()106 void SaveLogs()
107 {
108     std::string updaterLogPath = std::string(UPDATER_LOG);
109     std::string stageLogPath = std::string(UPDATER_STAGE_LOG);
110 
111     // save logs
112     bool ret = CopyUpdaterLogs(TMP_LOG, updaterLogPath);
113     if (!ret) {
114         LOG(ERROR) << "Copy updater log failed!";
115     }
116 
117     mode_t mode = 0660;
118 #ifndef __WIN32
119     SetFileAttributes(updaterLogPath, USER_UPDATE_AUTHORITY, GROUP_UPDATE_AUTHORITY, mode);
120 #endif
121 
122     STAGE(UPDATE_STAGE_SUCCESS) << "PostUpdater";
123     ret = CopyUpdaterLogs(TMP_STAGE_LOG, stageLogPath);
124     chmod(stageLogPath.c_str(), mode);
125     if (!ret) {
126         LOG(ERROR) << "Copy stage log failed!";
127     }
128 }
129 
DeleteFile(const std::string & filename)130 int32_t DeleteFile(const std::string& filename)
131 {
132     if (filename.empty()) {
133         LOG(ERROR) << "Invalid filename";
134         return -1;
135     }
136     if (unlink(filename.c_str()) == -1 && errno != ENOENT) {
137         LOG(ERROR) << "unlink " << filename << " failed";
138         return -1;
139     }
140     return 0;
141 }
142 
SplitString(const std::string & str,const std::string del)143 std::vector<std::string> SplitString(const std::string &str, const std::string del)
144 {
145     std::vector<std::string> result;
146     size_t found = std::string::npos;
147     size_t start = 0;
148     while (true) {
149         found = str.find_first_of(del, start);
150         result.push_back(str.substr(start, found - start));
151         if (found == std::string::npos) {
152             break;
153         }
154         start = found + 1;
155     }
156     return result;
157 }
158 
Trim(const std::string & str)159 std::string Trim(const std::string &str)
160 {
161     if (str.empty()) {
162         LOG(ERROR) << "str is empty";
163         return str;
164     }
165     size_t start = 0;
166     size_t end = str.size() - 1;
167     while (start < str.size()) {
168         if (!isspace(str[start])) {
169             break;
170         }
171         start++;
172     }
173     while (start < end) {
174         if (!isspace(str[end])) {
175             break;
176         }
177         end--;
178     }
179     if (end < start) {
180         return "";
181     }
182     return str.substr(start, end - start + 1);
183 }
184 
ConvertSha256Hex(const uint8_t * shaDigest,size_t length)185 std::string ConvertSha256Hex(const uint8_t* shaDigest, size_t length)
186 {
187     const std::string hexChars = "0123456789abcdef";
188     std::string haxSha256 = "";
189     unsigned int c;
190     for (size_t i = 0; i < length; ++i) {
191         auto d = shaDigest[i];
192         c = (d >> SHIFT_RIGHT_FOUR_BITS) & 0xf;     // last 4 bits
193         haxSha256.push_back(hexChars[c]);
194         haxSha256.push_back(hexChars[d & 0xf]);
195     }
196     return haxSha256;
197 }
198 
SetRebootMisc(const std::string & rebootTarget,const std::string & extData,struct UpdateMessage & msg)199 bool SetRebootMisc(const std::string& rebootTarget, const std::string &extData, struct UpdateMessage &msg)
200 {
201     static const int32_t maxCommandSize = 16;
202     int result = 0;
203     if (rebootTarget == "updater" && strcmp(msg.command, "boot_updater") != 0) {
204         result = strcpy_s(msg.command, maxCommandSize, "boot_updater");
205     } else if (rebootTarget == "flashd" && strcmp(msg.command, "flashd") != 0) {
206         result = strcpy_s(msg.command, maxCommandSize, "boot_flash");
207     } else if (rebootTarget == "bootloader" && strcmp(msg.command, "boot_loader") != 0) {
208         result = strcpy_s(msg.command, maxCommandSize, "boot_loader");
209     }
210     if (result != EOK) {
211         LOG(ERROR) << "reboot set misc strcpy failed";
212         return false;
213     }
214     msg.command[maxCommandSize] = 0;
215     if (extData.empty()) {
216         (void)memset_s(msg.update, sizeof(msg.update), 0, sizeof(msg.update));
217         return true;
218     }
219     if (strcpy_s(msg.update, sizeof(msg.update) - 1, extData.c_str()) != EOK) {
220         LOG(ERROR) << "failed to copy update";
221         return false;
222     }
223     msg.update[sizeof(msg.update) - 1] = 0;
224     return true;
225 }
226 
UpdaterDoReboot(const std::string & rebootTarget,const std::string & extData)227 void UpdaterDoReboot(const std::string& rebootTarget, const std::string &extData)
228 {
229     LOG(INFO) << ", rebootTarget: " << rebootTarget;
230     LoadFstab();
231     struct UpdateMessage msg = {};
232     if (rebootTarget.empty()) {
233         if (WriteUpdaterMiscMsg(msg) != true) {
234             LOG(INFO) << "UpdaterDoReboot: WriteUpdaterMessage empty error";
235             return;
236         }
237     } else {
238         if (!ReadUpdaterMiscMsg(msg)) {
239             LOG(ERROR) << "UpdaterDoReboot read misc failed";
240             return;
241         }
242         if (!SetRebootMisc(rebootTarget, extData, msg)) {
243             LOG(ERROR) << "UpdaterDoReboot set misc failed";
244             return;
245         }
246         if (!WriteUpdaterMiscMsg(msg)) {
247             LOG(INFO) << "UpdaterDoReboot: WriteUpdaterMiscMsg error";
248             return;
249         }
250     }
251     sync();
252 #ifndef UPDATER_UT
253     DoReboot(rebootTarget.c_str());
254     while (true) {
255         pause();
256     }
257 #else
258     return;
259 #endif
260 }
261 
DoShutdown()262 void DoShutdown()
263 {
264     UpdateMessage msg = {};
265     if (!WriteUpdaterMiscMsg(msg)) {
266         LOG(ERROR) << "DoShutdown: WriteUpdaterMessage empty error";
267         return;
268     }
269     sync();
270     DoReboot("shutdown");
271 }
272 
GetCertName()273 std::string GetCertName()
274 {
275 #ifndef UPDATER_UT
276     static std::string signingCertName = "/etc/certificate/signing_cert.crt";
277 #ifdef SIGN_ON_SERVER
278     signingCertName = Updater::Utils::ON_SERVER;
279 #endif
280 #else
281     static std::string signingCertName = "/data/updater/src/signing_cert.crt";
282 #endif
283     return signingCertName;
284 }
285 
WriteFully(int fd,const uint8_t * data,size_t size)286 bool WriteFully(int fd, const uint8_t *data, size_t size)
287 {
288     ssize_t written = 0;
289     size_t rest = size;
290 
291     while (rest > 0) {
292         do {
293             written = write(fd, data, rest);
294         } while (written < 0 && errno == EINTR);
295         if (written < 0) {
296             return false;
297         }
298         data += written;
299         rest -= static_cast<size_t>(written);
300         if (rest != 0) {
301             LOG(INFO) << "totalSize =  " << size << ", rest =  " << rest;
302         }
303     }
304     return true;
305 }
306 
ReadFully(int fd,void * data,size_t size)307 bool ReadFully(int fd, void *data, size_t size)
308 {
309     auto p = reinterpret_cast<uint8_t *>(data);
310     size_t remaining = size;
311     while (remaining > 0) {
312         ssize_t sread = read(fd, p, remaining);
313         if (sread == -1) {
314             LOG(ERROR) << "read failed: " << strerror(errno);
315             return false;
316         }
317         if (sread == 0) {
318             LOG(ERROR) << "read reached unexpected EOF";
319             return false;
320         }
321         p += sread;
322         remaining -= static_cast<size_t>(sread);
323     }
324     return true;
325 }
326 
ReadFileToString(int fd,std::string & content)327 bool ReadFileToString(int fd, std::string &content)
328 {
329     struct stat sb {};
330     if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
331         content.resize(static_cast<size_t>(sb.st_size));
332     }
333     ssize_t n;
334     auto remaining = static_cast<size_t>(sb.st_size);
335     auto p = reinterpret_cast<char *>(content.data());
336     while (remaining > 0) {
337         n = read(fd, p, remaining);
338         if (n <= 0) {
339             return false;
340         }
341         p += n;
342         remaining -= static_cast<size_t>(n);
343     }
344     return true;
345 }
346 
WriteStringToFile(int fd,const std::string & content)347 bool WriteStringToFile(int fd, const std::string& content)
348 {
349     const char *p = content.data();
350     size_t remaining = content.size();
351     while (remaining > 0) {
352         ssize_t n = write(fd, p, remaining);
353         if (n == -1) {
354             return false;
355         }
356         p += n;
357         remaining -= static_cast<size_t>(n);
358     }
359     return true;
360 }
361 
SyncFile(const std::string & dst)362 void SyncFile(const std::string &dst)
363 {
364     int fd = open(dst.c_str(), O_RDWR);
365     if (fd < 0) {
366         LOG(ERROR) << "open " << dst << " failed! err " << strerror(errno);
367         return;
368     }
369     fsync(fd);
370     close(fd);
371 }
372 
CopyFile(const std::string & src,const std::string & dest,bool isAppend)373 bool CopyFile(const std::string &src, const std::string &dest, bool isAppend)
374 {
375     char realPath[PATH_MAX + 1] = {0};
376     if (realpath(src.c_str(), realPath) == nullptr) {
377         LOG(ERROR) << src << " get realpath fail";
378         return false;
379     }
380 
381     std::ios_base::openmode mode = isAppend ? std::ios::app | std::ios::out : std::ios_base::out;
382     std::ifstream fin(realPath);
383     std::ofstream fout(dest, mode);
384     if (!fin.is_open() || !fout.is_open()) {
385         return false;
386     }
387 
388     fout << fin.rdbuf();
389     if (fout.fail()) {
390         fout.clear();
391         return false;
392     }
393     fout.flush();
394     fout.close();
395     SyncFile(dest); // no way to get fd from ofstream, so reopen to sync this file
396     return true;
397 }
398 
CopyDir(const std::string & srcPath,const std::string & dstPath)399 bool CopyDir(const std::string &srcPath, const std::string &dstPath)
400 {
401     DIR *dir = opendir(srcPath.c_str());
402     if (dir == nullptr) {
403         LOG(ERROR) << "opendir failed, path: " << srcPath.c_str() << ", err: " << strerror(errno);
404         return false;
405     }
406     ON_SCOPE_EXIT(closedir) {
407         closedir(dir);
408     };
409     bool existFlag = (access(dstPath.c_str(), 0) == 0);
410     if ((!existFlag) && (mkdir(dstPath.c_str(), DEFAULT_DIR_MODE) != 0)) {
411         LOG(ERROR) << "mkdir failed, path: " << dstPath.c_str() << ", err: " << strerror(errno);
412         return false;
413     }
414     ON_SCOPE_EXIT(rmdir) {
415         if (!existFlag) {
416             remove(dstPath.c_str());
417         }
418     };
419     dirent *dirent = nullptr;
420     while ((dirent = readdir(dir)) != nullptr) {
421         if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) {
422             continue;
423         }
424         if (dirent->d_type == DT_DIR) {
425             std::string fullSourcePath = srcPath + dirent->d_name + "/";
426             std::string fullDestPath = dstPath + dirent->d_name + "/";
427             if (!CopyDir(fullSourcePath, fullDestPath)) {
428                 LOG(ERROR) << "copydir failed, fullSourcePath: " << fullSourcePath.c_str()
429                           << ", fullDestPath: " << fullDestPath.c_str();
430                 return false;
431             }
432         } else {
433             std::string fullSourcePath = srcPath + dirent->d_name;
434             std::string fullDestPath = dstPath + dirent->d_name;
435             if (!CopyFile(fullSourcePath, fullDestPath)) {
436                 LOG(ERROR) << "copyfile failed, fullSourcePath: " << fullSourcePath.c_str()
437                           << ", fullDestPath: " << fullDestPath.c_str();
438                 return false;
439             }
440         }
441     }
442     CANCEL_SCOPE_EXIT_GUARD(rmdir);
443     return true;
444 }
445 
GetLocalBoardId()446 std::string GetLocalBoardId()
447 {
448     return "HI3516";
449 }
450 
CreateCompressLogFile(const std::string & pkgName,std::vector<std::pair<std::string,ZipFileInfo>> & files)451 int32_t CreateCompressLogFile(const std::string &pkgName, std::vector<std::pair<std::string, ZipFileInfo>> &files)
452 {
453     PkgInfo pkgInfo;
454     pkgInfo.signMethod = PKG_SIGN_METHOD_NONE;
455     pkgInfo.digestMethod = PKG_SIGN_METHOD_NONE;
456     pkgInfo.pkgType = PKG_PACK_TYPE_ZIP;
457     PkgManager::PkgManagerPtr pkgManager = PkgManager::CreatePackageInstance();
458     if (pkgManager == nullptr) {
459         LOG(ERROR) << "pkgManager is nullptr";
460         return -1;
461     }
462     int32_t ret = pkgManager->CreatePackage(pkgName, GetCertName(), &pkgInfo, files);
463     PkgManager::ReleasePackageInstance(pkgManager);
464     return ret;
465 }
466 
CompressFiles(std::vector<std::string> & files,const std::string & zipFile)467 void CompressFiles(std::vector<std::string> &files, const std::string &zipFile)
468 {
469     (void)DeleteFile(zipFile);
470     std::vector<std::pair<std::string, ZipFileInfo>> zipFiles {};
471     for (auto path : files) {
472         ZipFileInfo file {};
473         file.fileInfo.identity = path.substr(path.find_last_of("/") + 1);
474         file.fileInfo.packMethod = PKG_COMPRESS_METHOD_ZIP;
475         file.fileInfo.digestMethod = PKG_DIGEST_TYPE_CRC;
476         zipFiles.push_back(std::pair<std::string, ZipFileInfo>(path, file));
477     }
478 
479     int32_t ret = CreateCompressLogFile(zipFile, zipFiles);
480     if (ret != 0) {
481         LOG(WARNING) << "CompressFiles failed: " << zipFile;
482         return;
483     }
484     mode_t mode = 0660;
485 #ifndef __WIN32
486     SetFileAttributes(zipFile, USER_UPDATE_AUTHORITY, GROUP_SYS_AUTHORITY, mode);
487 #endif
488 }
489 
CompressLogs(const std::string & logName)490 void CompressLogs(const std::string &logName)
491 {
492     std::vector<std::pair<std::string, ZipFileInfo>> files;
493     // Build the zip file to be packaged
494     std::vector<std::string> testFileNames;
495     std::string realName = logName.substr(logName.find_last_of("/") + 1);
496     std::string logPath = logName.substr(0, logName.find_last_of("/"));
497     testFileNames.push_back(realName);
498     for (auto name : testFileNames) {
499         ZipFileInfo file;
500         file.fileInfo.identity = name;
501         file.fileInfo.packMethod = PKG_COMPRESS_METHOD_ZIP;
502         file.fileInfo.digestMethod = PKG_DIGEST_TYPE_CRC;
503         std::string fileName = logName;
504         files.push_back(std::pair<std::string, ZipFileInfo>(fileName, file));
505     }
506 
507     char realTime[MAX_TIME_SIZE] = {0};
508     auto sysTime = std::chrono::system_clock::now();
509     auto currentTime = std::chrono::system_clock::to_time_t(sysTime);
510     struct tm *localTime = std::localtime(&currentTime);
511     if (localTime != nullptr) {
512         std::strftime(realTime, sizeof(realTime), "%Y%m%d%H%M%S", localTime);
513     }
514     char pkgName[MAX_LOG_NAME_SIZE];
515     if (snprintf_s(pkgName, MAX_LOG_NAME_SIZE, MAX_LOG_NAME_SIZE - 1,
516         "%s/%s_%s.zip", logPath.c_str(), realName.c_str(), realTime) == -1) {
517         return;
518     }
519     int32_t ret = CreateCompressLogFile(pkgName, files);
520     if (ret != 0) {
521         LOG(WARNING) << "CompressLogs failed";
522         return;
523     }
524     mode_t mode = 0660;
525 #ifndef __WIN32
526     SetFileAttributes(pkgName, USER_UPDATE_AUTHORITY, GROUP_SYS_AUTHORITY, mode);
527 #endif
528     sync();
529     if (access(pkgName, 0) != 0) {
530         LOG(ERROR) << "Failed to create zipfile: " << pkgName;
531     } else {
532         (void)DeleteFile(logName);
533     }
534 }
535 
GetFileSize(const std::string & filePath)536 size_t GetFileSize(const std::string &filePath)
537 {
538     int ret = 0;
539     std::ifstream ifs(filePath, std::ios::binary | std::ios::in);
540     if (ifs.is_open()) {
541         ifs.seekg(0, std::ios::end);
542         ret = ifs.tellg();
543     }
544     return ret;
545 }
546 
RestoreconPath(const std::string & path)547 bool RestoreconPath(const std::string &path)
548 {
549     if (MountForPath(path) != 0) {
550         LOG(ERROR) << "MountForPath " << path << " failed!";
551         return false;
552     }
553 #ifdef WITH_SELINUX
554     if (RestoreconRecurse(path.c_str()) == -1) {
555         LOG(WARNING) << "restore " << path << " failed";
556     }
557 #endif // WITH_SELINUX
558     if (UmountForPath(path) != 0) {
559         LOG(WARNING) << "UmountForPath " << path << " failed!";
560     }
561     return true;
562 }
563 
CopyUpdaterLogs(const std::string & sLog,const std::string & dLog)564 bool CopyUpdaterLogs(const std::string &sLog, const std::string &dLog)
565 {
566     std::size_t found = dLog.find_last_of("/");
567     if (found == std::string::npos) {
568         LOG(ERROR) << "Dest filePath error";
569         return false;
570     }
571     std::string destPath = dLog.substr(0, found);
572     if (MountForPath(destPath) != 0) {
573         LOG(WARNING) << "MountForPath /data/log failed!";
574     }
575 
576     if (access(destPath.c_str(), 0) != 0) {
577         if (MkdirRecursive(destPath.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
578             LOG(ERROR) << "MkdirRecursive error!";
579             return false;
580         }
581         #ifdef WITH_SELINUX
582             RestoreconRecurse(UPDATER_PATH);
583         #endif // WITH_SELINUX
584     }
585 
586     if (Utils::GetFileSize(sLog) > MAX_LOG_SIZE) {
587         LOG(ERROR) << "Size bigger for" << sLog;
588         STAGE(UPDATE_STAGE_FAIL) << "Log file error, unable to copy";
589         return false;
590     }
591 
592     while (Utils::GetFileSize(sLog) + GetDirSizeForFile(dLog) > MAX_LOG_DIR_SIZE) {
593         if (DeleteOldFile(destPath) != true) {
594             break;
595         }
596     }
597 
598     if (!CopyFile(sLog, dLog, true)) {
599         LOG(ERROR) << "copy log file failed.";
600         return false;
601     }
602     if (GetFileSize(dLog) >= MAX_LOG_SIZE) {
603         LOG(INFO) << "log size greater than 5M!";
604         CompressLogs(dLog);
605     }
606     sync();
607     return true;
608 }
609 
CheckResultFail()610 bool CheckResultFail()
611 {
612     std::ifstream ifs;
613     const std::string resultPath = std::string(UPDATER_PATH) + "/" + std::string(UPDATER_RESULT_FILE);
614     ifs.open(resultPath, std::ios::in);
615     std::string buff;
616     while (ifs.is_open() && getline(ifs, buff)) {
617         if (buff.find("fail|") != std::string::npos) {
618             ifs.close();
619             return true;
620         }
621     }
622     LOG(ERROR) << "open result file failed";
623     return false;
624 }
625 
WriteDumpResult(const std::string & result,const std::string & fileName)626 void WriteDumpResult(const std::string &result, const std::string &fileName)
627 {
628     if (access(UPDATER_PATH, 0) != 0) {
629         if (MkdirRecursive(UPDATER_PATH, 0755) != 0) { // 0755: -rwxr-xr-x
630             LOG(ERROR) << "MkdirRecursive error!";
631             return;
632         }
633     }
634     const std::string resultPath = std::string(UPDATER_PATH) + "/" + fileName;
635     FILE *fp = fopen(resultPath.c_str(), "w+");
636     if (fp == nullptr) {
637         LOG(ERROR) << "open result file failed";
638         return;
639     }
640     char buf[MAX_RESULT_BUFF_SIZE] = "Pass\n";
641     if (sprintf_s(buf, MAX_RESULT_BUFF_SIZE - 1, "%s\n", result.c_str()) < 0) {
642         LOG(WARNING) << "sprintf status fialed";
643     }
644     if (fwrite(buf, 1, strlen(buf) + 1, fp) <= 0) {
645         LOG(WARNING) << "write result file failed, err:" << errno;
646     }
647     if (fclose(fp) != 0) {
648         LOG(WARNING) << "close result file failed";
649     }
650 
651     (void)chown(resultPath.c_str(), USER_ROOT_AUTHORITY, GROUP_UPDATE_AUTHORITY);
652     (void)chmod(resultPath.c_str(), 0660); // 0660: -rw-rw----
653 }
654 
GetDirSize(const std::string & folderPath)655 long long int GetDirSize(const std::string &folderPath)
656 {
657     DIR* dir = opendir(folderPath.c_str());
658     if (dir == nullptr) {
659         LOG(ERROR) << "Failed to open folder: " << folderPath << std::endl;
660         return 0;
661     }
662 
663     struct dirent* entry;
664     long long int totalSize = 0;
665     while ((entry = readdir(dir)) != nullptr) {
666         std::string fileName = entry->d_name;
667         std::string filePath = folderPath + "/" + fileName;
668         struct stat fileStat;
669         if (stat(filePath.c_str(), &fileStat) != 0) {
670             LOG(ERROR) << "Failed to get file status: " << filePath << std::endl;
671             continue;
672         }
673         if (S_ISDIR(fileStat.st_mode)) {
674             if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
675                 continue;
676             }
677             std::string subFolderPath = filePath;
678             totalSize += GetDirSize(subFolderPath);
679         } else {
680             totalSize += fileStat.st_size;
681         }
682     }
683     closedir(dir);
684     return totalSize;
685 }
686 
GetDirSizeForFile(const std::string & filePath)687 long long int GetDirSizeForFile(const std::string &filePath)
688 {
689     std::size_t found = filePath.find_last_of("/");
690     if (found == std::string::npos) {
691         LOG(ERROR) << "filePath error";
692         return -1;
693     }
694     return GetDirSize(filePath.substr(0, found));
695 }
696 
DeleteOldFile(const std::string folderPath)697 bool DeleteOldFile(const std::string folderPath)
698 {
699     DIR* dir = opendir(folderPath.c_str());
700     if (dir == nullptr) {
701         LOG(ERROR) << "Failed to open folder: " << folderPath << std::endl;
702         return false;
703     }
704 
705     struct dirent* entry;
706     std::string oldestFilePath = "";
707     time_t oldestFileTime = std::numeric_limits<time_t>::max();
708     while ((entry = readdir(dir)) != nullptr) {
709         std::string fileName = entry->d_name;
710         std::string filePath = folderPath + "/" + fileName;
711         struct stat fileStat;
712         if (stat(filePath.c_str(), &fileStat) != 0) {
713             LOG(ERROR) << "Failed to get file status: " << filePath;
714             continue;
715         }
716         if (fileName == "." || fileName == "..") {
717             continue;
718         }
719         if (fileStat.st_mtime < oldestFileTime) {
720             oldestFileTime = fileStat.st_mtime;
721             oldestFilePath = filePath;
722         }
723     }
724     closedir(dir);
725     if (oldestFilePath.empty()) {
726         LOG(ERROR) << "Unable to delete file";
727         return false;
728     }
729     size_t size = GetFileSize(oldestFilePath);
730     if (remove(oldestFilePath.c_str()) != 0) {
731         LOG(ERROR) << "Failed to delete file: " << oldestFilePath;
732         return false;
733     }
734     LOG(INFO) << "Delete old file: " << oldestFilePath << " size: " << size;
735     return true;
736 }
737 
ParseParams(int argc,char ** argv)738 std::vector<std::string> ParseParams(int argc, char **argv)
739 {
740     struct UpdateMessage boot {};
741     // read from misc
742     if (!ReadUpdaterMiscMsg(boot)) {
743         LOG(ERROR) << "ReadUpdaterMessage MISC_FILE failed!";
744     }
745     // if boot.update is empty, read from command.The Misc partition may have dirty data,
746     // so strlen(boot.update) is not used, which can cause system exceptions.
747     if (boot.update[0] == '\0' && !access(COMMAND_FILE, 0)) {
748         if (!ReadUpdaterMessage(COMMAND_FILE, boot)) {
749             LOG(ERROR) << "ReadUpdaterMessage COMMAND_FILE failed!";
750         }
751     }
752     STAGE(UPDATE_STAGE_OUT) << "Init Params: " << boot.update;
753     boot.update[sizeof(boot.update) - 1] = '\0';
754     std::vector<std::string> parseParams = Utils::SplitString(boot.update, "\n");
755     if (argc != 0 && argv != nullptr) {
756         parseParams.insert(parseParams.begin(), argv, argv + argc);
757     }
758     return parseParams;
759 }
760 
TrimUpdateMode(const std::string & mode)761 std::string TrimUpdateMode(const std::string &mode)
762 {
763     std::string optEqual = "=";
764     std::string modePrefix = "--"; // misc = --update_package=xxxx / --sdcard_update
765     size_t optPos = mode.size();
766     size_t prefixPos = 0;
767     if (mode.empty() || mode == "") {
768         return "";
769     }
770     if (mode.find(optEqual) != std::string::npos) {
771         optPos = mode.find(optEqual);
772     }
773     if (mode.find(modePrefix) != std::string::npos) {
774         prefixPos = mode.find(modePrefix) + modePrefix.size();
775     }
776     if (optPos < prefixPos) {
777         return mode;
778     }
779     return mode.substr(prefixPos, optPos - prefixPos);
780 }
781 
CheckUpdateMode(const std::string & mode)782 bool CheckUpdateMode(const std::string &mode)
783 {
784     std::vector<std::string> args = ParseParams(0, nullptr);
785     for (const auto &arg : args) {
786         if (TrimUpdateMode(arg) == mode) {
787             return true;
788         }
789     }
790     return false;
791 }
792 
DurationToString(std::vector<std::chrono::duration<double>> & durations,std::size_t pkgPosition,int precision)793 std::string DurationToString(std::vector<std::chrono::duration<double>> &durations, std::size_t pkgPosition,
794     int precision)
795 {
796     if (pkgPosition >= durations.size()) {
797         LOG(ERROR) << "pkg position is " << pkgPosition << ", duration's size is " << durations.size();
798         return "0";
799     }
800     std::ostringstream oss;
801     oss << std::fixed << std::setprecision(precision) << durations[pkgPosition].count();
802     return oss.str();
803 }
804 
GetRealPath(const std::string & path)805 std::string GetRealPath(const std::string &path)
806 {
807     char realPath[PATH_MAX + 1] = {0};
808     auto ret = realpath(path.c_str(), realPath);
809     return (ret == nullptr) ? "" : ret;
810 }
811 
GetPartitionRealPath(const std::string & name)812 std::string GetPartitionRealPath(const std::string &name)
813 {
814     return GetRealPath(PREFIX_PARTITION_NODE + name);
815 }
816 
SetMessageToMisc(const std::string & miscCmd,const int message,const std::string headInfo)817 void SetMessageToMisc(const std::string &miscCmd, const int message, const std::string headInfo)
818 {
819     if (headInfo.empty()) {
820         return;
821     }
822     std::vector<std::string> args = ParseParams(0, nullptr);
823     struct UpdateMessage msg {};
824     if (!ReadUpdaterMiscMsg(msg)) {
825         LOG(ERROR) << "SetMessageToMisc read misc failed";
826         return;
827     }
828     (void)memset_s(msg.command, sizeof(msg.command), 0, sizeof(msg.command));
829     if (strncpy_s(msg.command, sizeof(msg.command), miscCmd.c_str(), miscCmd.size() + 1) != EOK) {
830         LOG(ERROR) << "SetMessageToMisc strncpy_s failed";
831         return;
832     }
833     (void)memset_s(msg.update, sizeof(msg.update), 0, sizeof(msg.update));
834     for (const auto& arg : args) {
835         if (arg.find(headInfo) == std::string::npos) {
836             if (strncat_s(msg.update, sizeof(msg.update), arg.c_str(), strlen(arg.c_str()) + 1) != EOK) {
837                 LOG(ERROR) << "SetMessageToMisc strncat_s failed";
838                 return;
839             }
840             if (strncat_s(msg.update, sizeof(msg.update), "\n", strlen("\n") + 1) != EOK) {
841                 LOG(ERROR) << "SetMessageToMisc strncat_s failed";
842                 return;
843             }
844         }
845     }
846     char buffer[128] {}; // 128 : set headInfo size
847     if (headInfo == "sdcard_update") {
848         if (snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, "--%s", headInfo.c_str()) == -1) {
849             LOG(ERROR) << "SetMessageToMisc snprintf_s failed";
850             return;
851         }
852     } else {
853         if (snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, "--%s=%d", headInfo.c_str(), message) == -1) {
854             LOG(ERROR) << "SetMessageToMisc snprintf_s failed";
855             return;
856         }
857     }
858     if (strncat_s(msg.update, sizeof(msg.update), buffer, strlen(buffer) + 1) != EOK) {
859         LOG(ERROR) << "SetMessageToMisc strncat_s failed";
860         return;
861     }
862     if (WriteUpdaterMiscMsg(msg) != true) {
863         LOG(ERROR) << "Write command to misc failed.";
864     }
865 }
866 
SetCmdToMisc(const std::string & miscCmd)867 void SetCmdToMisc(const std::string &miscCmd)
868 {
869     struct UpdateMessage msg {};
870     if (!ReadUpdaterMiscMsg(msg)) {
871         LOG(ERROR) << "SetMessageToMisc read misc failed";
872         return;
873     }
874 
875     (void)memset_s(msg.command, sizeof(msg.command), 0, sizeof(msg.command));
876     if (strncpy_s(msg.command, sizeof(msg.command), miscCmd.c_str(), miscCmd.size() + 1) != EOK) {
877         LOG(ERROR) << "SetMessageToMisc strncpy_s failed";
878         return;
879     }
880 
881     if (WriteUpdaterMiscMsg(msg) != true) {
882         LOG(ERROR) << "Write command to misc failed.";
883     }
884 }
885 
AddUpdateInfoToMisc(const std::string headInfo,const std::optional<int> message)886 void AddUpdateInfoToMisc(const std::string headInfo, const std::optional<int> message)
887 {
888     UpdateInfoInMisc(headInfo, message, false);
889 }
890 
RemoveUpdateInfoFromMisc(const std::string & headInfo)891 void RemoveUpdateInfoFromMisc(const std::string &headInfo)
892 {
893     UpdateInfoInMisc(headInfo, std::nullopt, true);
894 }
895 
SetFaultInfoToMisc(const std::string & faultInfo)896 void SetFaultInfoToMisc(const std::string &faultInfo)
897 {
898     struct UpdateMessage msg {};
899     if (!ReadUpdaterMiscMsg(msg)) {
900         LOG(ERROR) << "SetMessageToMisc read misc failed";
901         return;
902     }
903 
904     (void)memset_s(msg.faultinfo, sizeof(msg.faultinfo), 0, sizeof(msg.faultinfo));
905     if (strncpy_s(msg.faultinfo, sizeof(msg.faultinfo), faultInfo.c_str(), faultInfo.size() + 1) != EOK) {
906         LOG(ERROR) << "SetMessageToMisc strncpy_s failed";
907         return;
908     }
909 
910     if (WriteUpdaterMiscMsg(msg) != true) {
911         LOG(ERROR) << "Write fault info to misc failed.";
912     }
913 }
914 
CheckFaultInfo(const std::string & faultInfo)915 bool CheckFaultInfo(const std::string &faultInfo)
916 {
917     struct UpdateMessage msg = {};
918     if (!ReadUpdaterMiscMsg(msg)) {
919         LOG(ERROR) << "read misc data failed";
920         return false;
921     }
922 
923     if (strcmp(msg.faultinfo, faultInfo.c_str()) == 0) {
924         return true;
925     }
926     return false;
927 }
928 
GetTagValInStr(const std::string & str,const std::string & tag,std::string & val)929 void GetTagValInStr(const std::string &str, const std::string &tag, std::string &val)
930 {
931     if (str.find(tag + "=") != std::string::npos) {
932         val = str.substr(str.find("=") + 1, str.size() - str.find("="));
933     }
934 }
935 
IsValidHexStr(const std::string & str)936 bool IsValidHexStr(const std::string &str)
937 {
938     for (const auto &ch : str) {
939         if (isxdigit(ch) == 0) {
940             return false;
941         }
942     }
943     return true;
944 }
945 
TrimString(std::string & str)946 void TrimString(std::string &str)
947 {
948     auto pos = str.find_last_not_of("\r\n");
949     if (pos != std::string::npos) {
950         str.erase(pos + 1, str.size() - pos);
951     }
952 }
953 
IsEsDevice()954 bool IsEsDevice()
955 {
956     char deviceType[PARAM_SIZE + 1] = {0};
957     if (GetParameter("ohos.boot.chiptype", "", deviceType, sizeof(deviceType) - 1) <= 0) {
958         LOG(ERROR) << "get device type failed";
959         return false;
960     }
961     LOG(INFO) << "device type is " << deviceType;
962     if (strstr(deviceType, "_es") == nullptr) {
963         return false;
964     }
965     return true;
966 }
967 
968 #ifndef __WIN32
SetFileAttributes(const std::string & file,uid_t owner,gid_t group,mode_t mode)969 void SetFileAttributes(const std::string& file, uid_t owner, gid_t group, mode_t mode)
970 {
971 #ifdef WITH_SELINUX
972     RestoreconRecurse(file.c_str());
973 #endif // WITH_SELINUX
974     if (chown(file.c_str(), USER_ROOT_AUTHORITY, GROUP_ROOT_AUTHORITY) != 0) {
975         LOG(WARNING) << "Chown failed: " << file << " " << USER_ROOT_AUTHORITY << "," << GROUP_ROOT_AUTHORITY;
976     }
977     if (chmod(file.c_str(), mode) != EOK) {
978         LOG(WARNING) << "Chmod failed: " << file << " " << mode;
979     }
980     if (chown(file.c_str(), owner, group) != 0) {
981         LOG(WARNING) << "Chown failed: " << file << " " << owner << "," << group;
982     }
983 }
984 #endif
985 
986 } // Utils
InitLogger(const std::string & tag)987 void __attribute__((weak)) InitLogger(const std::string &tag)
988 {
989     if (Utils::IsUpdaterMode()) {
990         InitUpdaterLogger(tag, TMP_LOG, TMP_STAGE_LOG, TMP_ERROR_CODE_PATH);
991     } else {
992         InitUpdaterLogger(tag, SYS_INSTALLER_LOG, UPDATER_STAGE_LOG, ERROR_CODE_PATH);
993     }
994 }
995 } // namespace Updater
996