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>
27 #include <openssl/evp.h>
28 #include <openssl/crypto.h>
35 #include <unordered_map>
45 #include "path_manager.h"
47 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
49 return static_cast<int>(a.length()) - length >= aOffset &&
50 static_cast<int>(b.length()) - length >= bOffset &&
51 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
52 [](unsigned char a, unsigned char b)
53 { return std::tolower(a) == std::tolower(b); });
56 bool isManagedAssembly(const std::string& fileName)
58 return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) && !isNativeImage(fileName);
61 bool isNativeImage(const std::string& fileName)
63 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
66 std::string concatPath(const std::string& path1, const std::string& path2)
68 std::string path(path1);
69 if (path.back() == PATH_SEPARATOR) {
72 path += PATH_SEPARATOR;
79 void splitPath(const std::string& path, std::vector<std::string>& out)
81 std::istringstream ss(path);
84 while (std::getline(ss, token, ':')) {
89 std::string getAbsolutePath(const std::string& path)
92 char *realPath = realpath(path.c_str(), NULL);
94 absPath.assign(realPath);
101 std::string getRootPath(const std::string& pkgId)
105 std::string rootPath;
107 pkgmgrinfo_pkginfo_h pkg_handle;
108 ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
113 ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
114 if (ret != PMINFO_R_OK) {
115 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
119 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
124 std::string getExecName(const std::string& pkgId)
128 std::string execName;
130 pkgmgrinfo_pkginfo_h pkg_handle;
131 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
136 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
137 if (ret != PMINFO_R_OK) {
138 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
142 pkgmgrinfo_appinfo_h app_handle;
143 ret = pkgmgrGetAppInfo(appId, &app_handle);
145 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
149 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
150 if (ret != PMINFO_R_OK) {
151 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
152 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
155 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
157 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
158 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
163 std::string getAppType(const std::string& pkgId)
169 pkgmgrinfo_pkginfo_h pkg_handle;
170 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
175 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
176 if (ret != PMINFO_R_OK) {
177 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
181 pkgmgrinfo_appinfo_h app_handle;
182 ret = pkgmgrGetAppInfo(appId, &app_handle);
184 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
188 ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
189 if (ret != PMINFO_R_OK) {
190 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
191 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
196 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
197 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
202 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
206 std::string metadataValue;
208 pkgmgrinfo_pkginfo_h pkg_handle;
209 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
211 return metadataValue;
214 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
215 if (ret != PMINFO_R_OK) {
216 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
217 return metadataValue;
220 pkgmgrinfo_appinfo_h app_handle;
221 ret = pkgmgrGetAppInfo(appId, &app_handle);
223 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
224 return metadataValue;
227 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
228 if (ret != PMINFO_R_OK) {
229 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
230 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
231 return metadataValue;
233 metadataValue = std::string(value);
235 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
236 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
238 return metadataValue;
241 bool isReadOnlyArea(const std::string& path)
244 struct mntent *m = NULL;
246 // "/opt/usr" is mounted to "RW" only
247 if (path.find("/opt/usr") != std::string::npos) {
251 // check whether "/" is mounted to RO or not
252 f = setmntent("/proc/mounts", "r");
254 // return true for fail case to generate NI files under RW area.
258 while((m = getmntent(f))) {
259 if (m->mnt_dir != NULL && strcmp(m->mnt_dir, "/") == 0 &&
260 m->mnt_opts != NULL && strstr(m->mnt_opts, "ro,") != NULL) {
270 std::string getBaseName(const std::string& path)
272 auto pos = path.find_last_of(PATH_SEPARATOR);
273 if (pos != std::string::npos)
274 return path.substr(0, pos);
276 return std::string(".");
280 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
282 std::string result = str;
283 std::string::size_type pos = 0;
284 std::string::size_type offset = 0;
286 while ((pos = result.find(pattern, offset)) != std::string::npos) {
287 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
288 offset = pos + replace.size();
294 std::string changeExtension(const std::string& path, const std::string& from, const std::string& to)
296 return path.substr(0, path.rfind(from)) + to;
299 bool isFile(const std::string& path)
302 return lstat(path.c_str(), &sb) == 0;
305 bool isSymlinkFile(const std::string& path)
308 if (lstat(path.c_str(), &sb) != 0) {
311 return (sb.st_mode & S_IFMT) == S_IFLNK;
314 bool isDirectory(const std::string& path)
317 if (stat(path.c_str(), &sb) != 0) {
320 return (sb.st_mode & S_IFMT) == S_IFDIR;
323 std::string getAssemblyNameFromPath(const std::string& path)
325 std::string ret(getFileName(path));
327 if (ret.find_last_of(".") == std::string::npos)
329 ret.erase(ret.find_last_of("."));
331 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
332 ret.erase(ret.size() - 3);
337 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
339 std::vector<std::string> assems;
340 std::unordered_map<std::string, std::string> assemPaths;
342 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
343 if (isManagedAssembly(filename) || isNativeImage(filename)) {
344 std::string assem = getAssemblyNameFromPath(filename);
346 if (assemPaths.count(assem) == 0) {
347 assems.push_back(assem);
348 assemPaths[assem] = path;
349 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
350 // Update only if a native image is found in the same directory.
351 // For example, if we have two directories = { X, Y } where X contains A.dll and
352 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
353 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
354 assemPaths[assem] = path;
358 for (auto& directory : directories)
359 scanFilesInDirectory(directory, reader, 0);
361 if (!list.empty() && list.back() != ':')
364 for (auto& assem : assems)
365 list += assemPaths[assem] + ":";
367 if (list.back() == ':')
371 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
374 struct dirent* entry;
377 dir = opendir(directory.c_str());
382 std::vector<std::string> innerDirectories;
384 while ((entry = readdir(dir)) != nullptr) {
386 std::string path = concatPath(directory, entry->d_name);
387 switch (entry->d_type) {
392 // symlink is added to the list even if there is no original file.
393 // It used to remove broken symlinks related to TAC
402 reader(path, entry->d_name);
403 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
404 innerDirectories.push_back(path);
408 for (auto& d : innerDirectories)
409 scanFilesInDirectory(d, reader, depth - 1);
414 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
420 // change smack label for symbolic link.
421 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
422 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
423 _SERR("Fail to set smack label");
428 // change owner and groupsfor symbolic link.
429 // change mode is skipped for symlink because permission of symlink file is meaningless.
430 if (!lstat(fromPath.c_str(), &info)) {
431 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
432 _SERR("Failed to change owner and group name");
435 // change smack label
436 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
437 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
438 _SERR("Fail to set smack label");
443 // change owner, groups and mode for generated ni file.
444 if (!stat(fromPath.c_str(), &info)) {
445 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
446 _SERR("Failed to change owner and group name");
447 if (chmod(toPath.c_str(), info.st_mode) == -1)
448 _SERR("Failed to change mode");
453 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
455 int fd = open(path.c_str(), O_RDONLY);
457 _ERR("Can't open directory: %s", path.c_str());
460 int ret = fchown(fd, uid, gid);
463 _ERR("Failed to change owner of: %s", path.c_str());
469 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
471 bs::error_code error;
472 bf::permissions(path, permissions, error);
474 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
480 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
482 if (!setOwnership(path, uid, gid)) {
483 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
486 if (!setDirPermissions(path, permissions)) {
487 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
493 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
496 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
499 bs::error_code error;
500 bf::perms permissions = bf::status(path, error).permissions();
502 _ERR("Failed to copy ownership and permissions : %s", error.message().c_str());
506 if (stat(path.c_str(), &stats) != 0) {
509 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
510 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
516 bool exist(const bf::path& path)
518 bs::error_code error;
519 int ret = bf::exists(path, error);
521 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
522 _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
528 bool createDir(const bf::path& path)
533 bs::error_code error;
534 bf::create_directories(path, error);
536 _ERR("Failed to create directory: %s", error.message().c_str());
542 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
545 // Check whether the function call is valid
546 if (!exist(path1) || !bf::is_directory(path1)) {
547 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
551 // Create the destination directory
552 if (!createDir(path2)) {
553 _ERR("Unable to create destination directory %s", path2.c_str());
556 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
557 copyOwnershipAndPermissions(path1, path2);
560 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
561 _ERR("Destination directory %s already exists", path2.c_str());
564 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
565 copyOwnershipAndPermissions(path1, path2);
568 } catch (const bf::filesystem_error& error) {
569 _ERR("Failed to copy directory: %s", error.what());
573 // Iterate through the source directory
575 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
576 bf::path current(file->path());
577 bf::path target = path2 / current.filename();
578 if (bf::is_symlink(bf::symlink_status(current))) {
579 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
582 bs::error_code error;
583 bf::copy_symlink(current, target, error);
585 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
588 } else if (bf::is_directory(current)) {
589 // Found directory: Recursion
590 if (!copyDir(current, target, flags)) {
594 if ((flags & FS_MERGE_SKIP) && exist(target)) {
597 bf::path destination = target;
598 if (flags & FS_COMMIT_COPY_FILE) {
599 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
601 if (flags & FS_MERGE_OVERWRITE) {
602 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
604 bf::copy_file(current, destination);
606 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
607 copyOwnershipAndPermissions(current, destination);
609 if (flags & FS_COMMIT_COPY_FILE) {
610 if (flags & FS_MERGE_OVERWRITE) {
613 bf::rename(destination, target);
617 } catch (const bf::filesystem_error& error) {
618 _ERR("Failed to copy directory: %s", error.what());
625 bool copyFile(const bf::path& path1, const bf::path& path2)
627 bs::error_code error;
631 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
633 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
639 bool moveFile(const bf::path& path1, const bf::path& path2)
641 if (!exist(path1) || exist(path2)) {
644 bs::error_code error;
645 bf::rename(path1, path2, error);
647 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
648 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
650 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
653 bf::remove_all(path1, error);
655 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
662 bool removeFile(const bf::path& path)
667 bs::error_code error;
668 bf::remove(path, error);
670 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
676 bool removeAll(const bf::path& path)
681 bs::error_code error;
682 bf::remove_all(path, error);
684 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
690 void setCmdName(const std::string& name)
692 #define PRC_NAME_LENGTH 16
694 char processName[PRC_NAME_LENGTH] = {0, };
699 memset(processName, '\0', PRC_NAME_LENGTH);
700 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
701 prctl(PR_SET_NAME, processName);
704 std::string getFileName(const std::string& path)
706 std::string ret(path);
707 size_t index = ret.find_last_of(PATH_SEPARATOR);
708 return index == std::string::npos ? ret : ret.substr(index + 1);
711 std::string SHA256(const std::string& path)
714 const int bufSize = 32768;
716 unsigned int digest_len = 0;
717 unsigned char* digest = NULL;
719 std::stringstream ss;
720 EVP_MD_CTX *mdctx = NULL;
721 std::string output = "";
723 FILE *file = fopen(path.c_str(), "rb");
728 char *buffer = (char*)malloc(bufSize);
733 mdctx = EVP_MD_CTX_new();
735 _ERR("Message Digest Context creation NULL");
739 digest = (unsigned char*)OPENSSL_malloc(EVP_MD_size(EVP_sha256()));
741 _ERR("Memory Allocation for SHA256 failed");
745 if (!EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) {
746 _ERR("Message Digest init failed");
750 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
751 if (!EVP_DigestUpdate(mdctx, buffer, bytesRead)) {
752 _ERR("Message Digest update failed");
757 if (!EVP_DigestFinal_ex(mdctx, digest, &digest_len)) {
758 _ERR("Message Digest Finalization falied");
762 for (unsigned int i = 0; i < digest_len; i++) {
763 ss << std::hex << std::setw(2) << std::setfill('0') << (int)digest[i];
768 EVP_MD_CTX_free(mdctx);
770 OPENSSL_free(digest);
779 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
784 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
785 _ERR("Failed to get UID");
789 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
790 if (ret != PMINFO_R_OK) {
791 _ERR("Failed to get pkginfo (%d)", ret);
798 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
803 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
804 _ERR("Failed to get UID");
808 ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
809 if (ret != PMINFO_R_OK) {
810 _ERR("Failed to get appinfo (%d)", ret);
817 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
818 pkgmgrinfo_app_list_cb app_cb,
824 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
825 _ERR("Failed to get UID");
830 ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
831 if (ret != PMINFO_R_OK) {
832 _ERR("Failed to execute the metadata filter query (%d)", ret);
839 void printHWClockLog(const char* format, ...)
841 char buf[1024] = {0,};
844 va_start(ap, format);
845 vsnprintf(buf, sizeof(buf), format, ap);
848 prctl(PR_TASK_PERF_USER_TRACE, buf, strlen(buf));
851 const char* getNCDBStartupHook()
853 return "/home/owner/share/tmp/sdk_tools/netcoredbg/ncdbhook.dll";
856 bool isNCDBStartupHookProvided()
859 env = getenv("DOTNET_STARTUP_HOOKS");
863 // Note, `DOTNET_STARTUP_HOOKS` env could provide list of dlls with ':' delimiter,
864 // for example: "/path1/name1.dll:/path2/name2.dll"
867 const char *ncdbCur = getNCDBStartupHook();
868 while (*ncdbCur != '\0' && *env != '\0' && *env != ':')
870 if (*ncdbCur != *env)
876 if (*ncdbCur == '\0' && (*env == '\0' || *env == ':'))
879 while (*env != '\0' && *env != ':')