2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 #include <pkgmgr_installer_info.h>
24 #include <sys/smack.h>
25 #include <sys/prctl.h>
26 #include <openssl/sha.h>
32 #include <unordered_map>
42 #include "path_manager.h"
44 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
46 return static_cast<int>(a.length()) - length >= aOffset &&
47 static_cast<int>(b.length()) - length >= bOffset &&
48 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
49 [](unsigned char a, unsigned char b)
50 { return std::tolower(a) == std::tolower(b); });
53 bool isManagedAssembly(const std::string& fileName)
55 return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) && !isNativeImage(fileName);
58 bool isNativeImage(const std::string& fileName)
60 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
63 std::string concatPath(const std::string& path1, const std::string& path2)
65 std::string path(path1);
66 if (path.back() == PATH_SEPARATOR) {
69 path += PATH_SEPARATOR;
76 void splitPath(const std::string& path, std::vector<std::string>& out)
78 std::istringstream ss(path);
81 while (std::getline(ss, token, ':')) {
86 std::string getAbsolutePath(const std::string& path)
89 char *realPath = realpath(path.c_str(), NULL);
91 absPath.assign(realPath);
98 std::string getRootPath(const std::string& pkgId)
102 std::string rootPath;
104 pkgmgrinfo_pkginfo_h pkg_handle;
105 ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
110 ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
111 if (ret != PMINFO_R_OK) {
112 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
116 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
121 std::string getExecName(const std::string& pkgId)
125 std::string execName;
127 pkgmgrinfo_pkginfo_h pkg_handle;
128 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
133 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
134 if (ret != PMINFO_R_OK) {
135 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
139 pkgmgrinfo_appinfo_h app_handle;
140 ret = pkgmgrGetAppInfo(appId, &app_handle);
142 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
146 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
147 if (ret != PMINFO_R_OK) {
148 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
149 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
152 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
154 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
155 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
160 std::string getAppType(const std::string& pkgId)
166 pkgmgrinfo_pkginfo_h pkg_handle;
167 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
172 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
173 if (ret != PMINFO_R_OK) {
174 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
178 pkgmgrinfo_appinfo_h app_handle;
179 ret = pkgmgrGetAppInfo(appId, &app_handle);
181 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
185 ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
186 if (ret != PMINFO_R_OK) {
187 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
188 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
193 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
194 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
199 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
203 std::string metadataValue;
205 pkgmgrinfo_pkginfo_h pkg_handle;
206 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
208 return metadataValue;
211 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
212 if (ret != PMINFO_R_OK) {
213 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
214 return metadataValue;
217 pkgmgrinfo_appinfo_h app_handle;
218 ret = pkgmgrGetAppInfo(appId, &app_handle);
220 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
221 return metadataValue;
224 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
225 if (ret != PMINFO_R_OK) {
226 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
227 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
228 return metadataValue;
230 metadataValue = std::string(value);
232 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
233 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
235 return metadataValue;
238 bool isReadOnlyArea(const std::string& path)
241 struct mntent *m = NULL;
243 // "/opt/usr" is mounted to "RW" only
244 if (path.find("/opt/usr") != std::string::npos) {
248 // check whether "/" is mounted to RO or not
249 f = setmntent("/proc/mounts", "r");
251 // return true for fail case to generate NI files under RW area.
255 while((m = getmntent(f))) {
256 if (m->mnt_dir != NULL && strcmp(m->mnt_dir, "/") == 0 &&
257 m->mnt_opts != NULL && strstr(m->mnt_opts, "ro,") != NULL) {
267 std::string getBaseName(const std::string& path)
269 auto pos = path.find_last_of(PATH_SEPARATOR);
270 if (pos != std::string::npos)
271 return path.substr(0, pos);
273 return std::string(".");
277 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
279 std::string result = str;
280 std::string::size_type pos = 0;
281 std::string::size_type offset = 0;
283 while ((pos = result.find(pattern, offset)) != std::string::npos) {
284 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
285 offset = pos + replace.size();
291 std::string changeExtension(const std::string& path, const std::string& from, const std::string& to)
293 return path.substr(0, path.rfind(from)) + to;
296 bool isFile(const std::string& path)
299 return lstat(path.c_str(), &sb) == 0;
302 bool isSymlinkFile(const std::string& path)
305 if (lstat(path.c_str(), &sb) != 0) {
308 return (sb.st_mode & S_IFMT) == S_IFLNK;
311 bool isDirectory(const std::string& path)
314 if (stat(path.c_str(), &sb) != 0) {
317 return (sb.st_mode & S_IFMT) == S_IFDIR;
320 std::string getAssemblyNameFromPath(const std::string& path)
322 std::string ret(getFileName(path));
324 if (ret.find_last_of(".") == std::string::npos)
326 ret.erase(ret.find_last_of("."));
328 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
329 ret.erase(ret.size() - 3);
334 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
336 std::vector<std::string> assems;
337 std::unordered_map<std::string, std::string> assemPaths;
339 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
340 if (isManagedAssembly(filename) || isNativeImage(filename)) {
341 std::string assem = getAssemblyNameFromPath(filename);
343 if (assemPaths.count(assem) == 0) {
344 assems.push_back(assem);
345 assemPaths[assem] = path;
346 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
347 // Update only if a native image is found in the same directory.
348 // For example, if we have two directories = { X, Y } where X contains A.dll and
349 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
350 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
351 assemPaths[assem] = path;
355 for (auto& directory : directories)
356 scanFilesInDirectory(directory, reader, 0);
358 if (!list.empty() && list.back() != ':')
361 for (auto& assem : assems)
362 list += assemPaths[assem] + ":";
364 if (list.back() == ':')
368 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
371 struct dirent* entry;
374 dir = opendir(directory.c_str());
379 std::vector<std::string> innerDirectories;
381 while ((entry = readdir(dir)) != nullptr) {
383 std::string path = concatPath(directory, entry->d_name);
384 switch (entry->d_type) {
389 // symlink is added to the list even if there is no original file.
390 // It used to remove broken symlinks related to TAC
399 reader(path, entry->d_name);
400 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
401 innerDirectories.push_back(path);
405 for (auto& d : innerDirectories)
406 scanFilesInDirectory(d, reader, depth - 1);
411 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
417 // change smack label for symbolic link.
418 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
419 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
420 _SERR("Fail to set smack label");
425 // change owner and groupsfor symbolic link.
426 // change mode is skipped for symlink because permission of symlink file is meaningless.
427 if (!lstat(fromPath.c_str(), &info)) {
428 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
429 _SERR("Failed to change owner and group name");
432 // change smack label
433 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
434 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
435 _SERR("Fail to set smack label");
440 // change owner, groups and mode for generated ni file.
441 if (!stat(fromPath.c_str(), &info)) {
442 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
443 _SERR("Failed to change owner and group name");
444 if (chmod(toPath.c_str(), info.st_mode) == -1)
445 _SERR("Failed to change mode");
450 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
452 int fd = open(path.c_str(), O_RDONLY);
454 _ERR("Can't open directory: %s", path.c_str());
457 int ret = fchown(fd, uid, gid);
460 _ERR("Failed to change owner of: %s", path.c_str());
466 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
468 bs::error_code error;
469 bf::permissions(path, permissions, error);
471 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
477 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
479 if (!setOwnership(path, uid, gid)) {
480 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
483 if (!setDirPermissions(path, permissions)) {
484 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
490 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
493 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
496 bs::error_code error;
497 bf::perms permissions = bf::status(path, error).permissions();
499 _ERR("Failed to copy ownership and permissions : %s", error.message().c_str());
503 if (stat(path.c_str(), &stats) != 0) {
506 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
507 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
513 bool exist(const bf::path& path)
515 bs::error_code error;
516 int ret = bf::exists(path, error);
518 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
519 _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
525 bool createDir(const bf::path& path)
530 bs::error_code error;
531 bf::create_directories(path, error);
533 _ERR("Failed to create directory: %s", error.message().c_str());
539 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
542 // Check whether the function call is valid
543 if (!exist(path1) || !bf::is_directory(path1)) {
544 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
548 // Create the destination directory
549 if (!createDir(path2)) {
550 _ERR("Unable to create destination directory %s", path2.c_str());
553 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
554 copyOwnershipAndPermissions(path1, path2);
557 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
558 _ERR("Destination directory %s already exists", path2.c_str());
561 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
562 copyOwnershipAndPermissions(path1, path2);
565 } catch (const bf::filesystem_error& error) {
566 _ERR("Failed to copy directory: %s", error.what());
570 // Iterate through the source directory
572 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
573 bf::path current(file->path());
574 bf::path target = path2 / current.filename();
575 if (bf::is_symlink(bf::symlink_status(current))) {
576 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
579 bs::error_code error;
580 bf::copy_symlink(current, target, error);
582 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
585 } else if (bf::is_directory(current)) {
586 // Found directory: Recursion
587 if (!copyDir(current, target, flags)) {
591 if ((flags & FS_MERGE_SKIP) && exist(target)) {
594 bf::path destination = target;
595 if (flags & FS_COMMIT_COPY_FILE) {
596 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
598 if (flags & FS_MERGE_OVERWRITE) {
599 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
601 bf::copy_file(current, destination);
603 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
604 copyOwnershipAndPermissions(current, destination);
606 if (flags & FS_COMMIT_COPY_FILE) {
607 if (flags & FS_MERGE_OVERWRITE) {
610 bf::rename(destination, target);
614 } catch (const bf::filesystem_error& error) {
615 _ERR("Failed to copy directory: %s", error.what());
622 bool copyFile(const bf::path& path1, const bf::path& path2)
624 bs::error_code error;
628 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
630 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
636 bool moveFile(const bf::path& path1, const bf::path& path2)
638 if (!exist(path1) || exist(path2)) {
641 bs::error_code error;
642 bf::rename(path1, path2, error);
644 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
645 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
647 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
650 bf::remove_all(path1, error);
652 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
659 bool removeFile(const bf::path& path)
664 bs::error_code error;
665 bf::remove(path, error);
667 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
673 bool removeAll(const bf::path& path)
678 bs::error_code error;
679 bf::remove_all(path, error);
681 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
687 void setCmdName(const std::string& name)
689 #define PRC_NAME_LENGTH 16
691 char processName[PRC_NAME_LENGTH] = {0, };
696 memset(processName, '\0', PRC_NAME_LENGTH);
697 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
698 prctl(PR_SET_NAME, processName);
701 std::string getFileName(const std::string& path)
703 std::string ret(path);
704 size_t index = ret.find_last_of(PATH_SEPARATOR);
705 return index == std::string::npos ? ret : ret.substr(index + 1);
708 std::string SHA256(const std::string& path)
710 std::string output = "";
711 FILE *file = fopen(path.c_str(), "rb");
716 unsigned char hash[SHA256_DIGEST_LENGTH];
718 SHA256_Init(&sha256);
720 const int bufSize = 32768;
721 char *buffer = (char*)malloc(bufSize);
727 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
728 SHA256_Update(&sha256, buffer, bytesRead);
730 SHA256_Final(hash, &sha256);
732 std::stringstream ss;
733 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
734 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
744 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
749 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
750 _ERR("Failed to get UID");
754 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
755 if (ret != PMINFO_R_OK) {
756 _ERR("Failed to get pkginfo (%d)", ret);
763 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
768 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
769 _ERR("Failed to get UID");
773 ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
774 if (ret != PMINFO_R_OK) {
775 _ERR("Failed to get appinfo (%d)", ret);
782 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
783 pkgmgrinfo_app_list_cb app_cb,
789 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
790 _ERR("Failed to get UID");
795 ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
796 if (ret != PMINFO_R_OK) {
797 _ERR("Failed to execute the metadata filter query (%d)", ret);
804 void printHWClockLog(const char* format, ...)
806 char buf[1024] = {0,};
809 va_start(ap, format);
810 vsnprintf(buf, sizeof(buf), format, ap);
813 prctl(PR_TASK_PERF_USER_TRACE, buf, strlen(buf));
816 const char* getNCDBStartupHook()
818 return "/home/owner/share/tmp/sdk_tools/netcoredbg/ncdbhook.dll";
821 bool isNCDBStartupHookProvided()
824 env = getenv("DOTNET_STARTUP_HOOKS");
828 // Note, `DOTNET_STARTUP_HOOKS` env could provide list of dlls with ':' delimiter,
829 // for example: "/path1/name1.dll:/path2/name2.dll"
832 const char *ncdbCur = getNCDBStartupHook();
833 while (*ncdbCur != '\0' && *env != '\0' && *env != ':')
835 if (*ncdbCur != *env)
841 if (*ncdbCur == '\0' && (*env == '\0' || *env == ':'))
844 while (*env != '\0' && *env != ':')