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) ||
56 iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
57 !isNativeImage(fileName);
60 bool isNativeImage(const std::string& fileName)
62 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
65 std::string concatPath(const std::string& path1, const std::string& path2)
67 std::string path(path1);
68 if (path.back() == PATH_SEPARATOR) {
71 path += PATH_SEPARATOR;
78 void splitPath(const std::string& path, std::vector<std::string>& out)
80 std::istringstream ss(path);
83 while (std::getline(ss, token, ':')) {
88 std::string getAbsolutePath(const std::string& path)
91 char *realPath = realpath(path.c_str(), NULL);
93 absPath.assign(realPath);
100 std::string getRootPath(const std::string& pkgId)
104 std::string rootPath;
106 pkgmgrinfo_pkginfo_h pkg_handle;
107 ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
112 ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
113 if (ret != PMINFO_R_OK) {
114 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
118 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
123 std::string getExecName(const std::string& pkgId)
127 std::string execName;
129 pkgmgrinfo_pkginfo_h pkg_handle;
130 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
135 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
136 if (ret != PMINFO_R_OK) {
137 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
141 pkgmgrinfo_appinfo_h app_handle;
142 ret = pkgmgrGetAppInfo(appId, &app_handle);
144 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
148 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
149 if (ret != PMINFO_R_OK) {
150 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
151 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
154 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
156 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
157 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
162 std::string getAppType(const std::string& pkgId)
168 pkgmgrinfo_pkginfo_h pkg_handle;
169 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
174 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
175 if (ret != PMINFO_R_OK) {
176 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
180 pkgmgrinfo_appinfo_h app_handle;
181 ret = pkgmgrGetAppInfo(appId, &app_handle);
183 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
187 ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
188 if (ret != PMINFO_R_OK) {
189 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
190 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
195 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
196 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
201 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
205 std::string metadataValue;
207 pkgmgrinfo_pkginfo_h pkg_handle;
208 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
210 return metadataValue;
213 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
214 if (ret != PMINFO_R_OK) {
215 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
216 return metadataValue;
219 pkgmgrinfo_appinfo_h app_handle;
220 ret = pkgmgrGetAppInfo(appId, &app_handle);
222 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
223 return metadataValue;
226 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
227 if (ret != PMINFO_R_OK) {
228 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
229 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
230 return metadataValue;
232 metadataValue = std::string(value);
234 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
235 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
237 return metadataValue;
240 bool isReadOnlyArea(const std::string& path)
243 struct mntent *m = NULL;
245 // "/opt/usr" is mounted to "RW" only
246 if (path.find("/opt/usr") != std::string::npos) {
250 // check whether "/" is mounted to RO or not
251 f = setmntent("/proc/mounts", "r");
253 // return true for fail case to generate NI files under RW area.
257 while((m = getmntent(f))) {
258 if (m->mnt_dir != NULL && strcmp(m->mnt_dir, "/") == 0 &&
259 m->mnt_opts != NULL && strstr(m->mnt_opts, "ro,") != NULL) {
269 std::string getBaseName(const std::string& path)
271 auto pos = path.find_last_of(PATH_SEPARATOR);
272 if (pos != std::string::npos)
273 return path.substr(0, pos);
275 return std::string(".");
279 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
281 std::string result = str;
282 std::string::size_type pos = 0;
283 std::string::size_type offset = 0;
285 while ((pos = result.find(pattern, offset)) != std::string::npos) {
286 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
287 offset = pos + replace.size();
293 std::string changeExtension(const std::string& path, const std::string& from, const std::string& to)
295 return path.substr(0, path.rfind(from)) + to;
298 bool isFile(const std::string& path)
301 return lstat(path.c_str(), &sb) == 0;
304 bool isSymlinkFile(const std::string& path)
307 if (lstat(path.c_str(), &sb) != 0) {
310 return (sb.st_mode & S_IFMT) == S_IFLNK;
313 bool isDirectory(const std::string& path)
316 if (stat(path.c_str(), &sb) != 0) {
319 return (sb.st_mode & S_IFMT) == S_IFDIR;
322 std::string getAssemblyNameFromPath(const std::string& path)
324 std::string ret(getFileName(path));
326 if (ret.find_last_of(".") == std::string::npos)
328 ret.erase(ret.find_last_of("."));
330 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
331 ret.erase(ret.size() - 3);
336 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
338 std::vector<std::string> assems;
339 std::unordered_map<std::string, std::string> assemPaths;
341 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
342 if (isManagedAssembly(filename) || isNativeImage(filename)) {
343 std::string assem = getAssemblyNameFromPath(filename);
345 if (assemPaths.count(assem) == 0) {
346 assems.push_back(assem);
347 assemPaths[assem] = path;
348 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
349 // Update only if a native image is found in the same directory.
350 // For example, if we have two directories = { X, Y } where X contains A.dll and
351 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
352 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
353 assemPaths[assem] = path;
357 for (auto& directory : directories)
358 scanFilesInDirectory(directory, reader, 0);
360 if (!list.empty() && list.back() != ':')
363 for (auto& assem : assems)
364 list += assemPaths[assem] + ":";
366 if (list.back() == ':')
370 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
373 struct dirent* entry;
376 dir = opendir(directory.c_str());
381 std::vector<std::string> innerDirectories;
383 while ((entry = readdir(dir)) != nullptr) {
385 std::string path = concatPath(directory, entry->d_name);
386 switch (entry->d_type) {
391 // symlink is added to the list even if there is no original file.
392 // It used to remove broken symlinks related to TAC
401 reader(path, entry->d_name);
402 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
403 innerDirectories.push_back(path);
407 for (auto& d : innerDirectories)
408 scanFilesInDirectory(d, reader, depth - 1);
413 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
419 // change smack label for symbolic link.
420 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
421 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
422 _SERR("Fail to set smack label");
427 // change owner and groupsfor symbolic link.
428 // change mode is skipped for symlink because permission of symlink file is meaningless.
429 if (!lstat(fromPath.c_str(), &info)) {
430 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
431 _SERR("Failed to change owner and group name");
434 // change smack label
435 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
436 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
437 _SERR("Fail to set smack label");
442 // change owner, groups and mode for generated ni file.
443 if (!stat(fromPath.c_str(), &info)) {
444 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
445 _SERR("Failed to change owner and group name");
446 if (chmod(toPath.c_str(), info.st_mode) == -1)
447 _SERR("Failed to change mode");
452 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
454 int fd = open(path.c_str(), O_RDONLY);
456 _ERR("Can't open directory: %s", path.c_str());
459 int ret = fchown(fd, uid, gid);
462 _ERR("Failed to change owner of: %s", path.c_str());
468 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
470 bs::error_code error;
471 bf::permissions(path, permissions, error);
473 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
479 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
481 if (!setOwnership(path, uid, gid)) {
482 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
485 if (!setDirPermissions(path, permissions)) {
486 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
492 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
495 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
498 bs::error_code error;
499 bf::perms permissions = bf::status(path, error).permissions();
501 _ERR("Failed to copy ownership and permissions : %s", error.message().c_str());
505 if (stat(path.c_str(), &stats) != 0) {
508 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
509 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
515 bool exist(const bf::path& path)
517 bs::error_code error;
518 int ret = bf::exists(path, error);
520 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
521 _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
527 bool createDir(const bf::path& path)
532 bs::error_code error;
533 bf::create_directories(path, error);
535 _ERR("Failed to create directory: %s", error.message().c_str());
541 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
544 // Check whether the function call is valid
545 if (!exist(path1) || !bf::is_directory(path1)) {
546 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
550 // Create the destination directory
551 if (!createDir(path2)) {
552 _ERR("Unable to create destination directory %s", path2.c_str());
555 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
556 copyOwnershipAndPermissions(path1, path2);
559 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
560 _ERR("Destination directory %s already exists", path2.c_str());
563 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
564 copyOwnershipAndPermissions(path1, path2);
567 } catch (const bf::filesystem_error& error) {
568 _ERR("Failed to copy directory: %s", error.what());
572 // Iterate through the source directory
574 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
575 bf::path current(file->path());
576 bf::path target = path2 / current.filename();
577 if (bf::is_symlink(bf::symlink_status(current))) {
578 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
581 bs::error_code error;
582 bf::copy_symlink(current, target, error);
584 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
587 } else if (bf::is_directory(current)) {
588 // Found directory: Recursion
589 if (!copyDir(current, target, flags)) {
593 if ((flags & FS_MERGE_SKIP) && exist(target)) {
596 bf::path destination = target;
597 if (flags & FS_COMMIT_COPY_FILE) {
598 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
600 if (flags & FS_MERGE_OVERWRITE) {
601 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
603 bf::copy_file(current, destination);
605 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
606 copyOwnershipAndPermissions(current, destination);
608 if (flags & FS_COMMIT_COPY_FILE) {
609 if (flags & FS_MERGE_OVERWRITE) {
612 bf::rename(destination, target);
616 } catch (const bf::filesystem_error& error) {
617 _ERR("Failed to copy directory: %s", error.what());
624 bool copyFile(const bf::path& path1, const bf::path& path2)
626 bs::error_code error;
630 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
632 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
638 bool moveFile(const bf::path& path1, const bf::path& path2)
640 if (!exist(path1) || exist(path2)) {
643 bs::error_code error;
644 bf::rename(path1, path2, error);
646 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
647 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
649 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
652 bf::remove_all(path1, error);
654 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
661 bool removeFile(const bf::path& path)
666 bs::error_code error;
667 bf::remove(path, error);
669 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
675 bool removeAll(const bf::path& path)
680 bs::error_code error;
681 bf::remove_all(path, error);
683 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
689 void setCmdName(const std::string& name)
691 #define PRC_NAME_LENGTH 16
693 char processName[PRC_NAME_LENGTH] = {0, };
698 memset(processName, '\0', PRC_NAME_LENGTH);
699 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
700 prctl(PR_SET_NAME, processName);
703 std::string getFileName(const std::string& path)
705 std::string ret(path);
706 size_t index = ret.find_last_of(PATH_SEPARATOR);
707 return index == std::string::npos ? ret : ret.substr(index + 1);
710 std::string SHA256(const std::string& path)
712 std::string output = "";
713 FILE *file = fopen(path.c_str(), "rb");
718 unsigned char hash[SHA256_DIGEST_LENGTH];
720 SHA256_Init(&sha256);
722 const int bufSize = 32768;
723 char *buffer = (char*)malloc(bufSize);
729 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
730 SHA256_Update(&sha256, buffer, bytesRead);
732 SHA256_Final(hash, &sha256);
734 std::stringstream ss;
735 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
736 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
746 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
751 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
752 _ERR("Failed to get UID");
756 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
757 if (ret != PMINFO_R_OK) {
758 _ERR("Failed to get pkginfo (%d)", ret);
765 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
770 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
771 _ERR("Failed to get UID");
775 ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
776 if (ret != PMINFO_R_OK) {
777 _ERR("Failed to get appinfo (%d)", ret);
784 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
785 pkgmgrinfo_app_list_cb app_cb,
791 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
792 _ERR("Failed to get UID");
797 ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
798 if (ret != PMINFO_R_OK) {
799 _ERR("Failed to execute the metadata filter query (%d)", ret);