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-info.h>
24 #include <pkgmgr_installer_info.h>
25 #include <sys/smack.h>
26 #include <sys/prctl.h>
27 #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)
105 std::string rootPath;
107 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
108 _ERR("Failed to get UID");
112 pkgmgrinfo_pkginfo_h handle;
114 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
115 if (ret != PMINFO_R_OK) {
119 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
120 if (ret != PMINFO_R_OK) {
125 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
126 if (ret != PMINFO_R_OK) {
127 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
131 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
136 std::string getExecName(const std::string& pkgId)
140 std::string execName;
142 pkgmgrinfo_pkginfo_h pkg_handle;
143 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
144 if (ret != PMINFO_R_OK) {
147 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
148 if (ret != PMINFO_R_OK) {
149 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
153 pkgmgrinfo_appinfo_h app_handle;
154 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
155 if (ret != PMINFO_R_OK) {
156 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
159 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
160 if (ret != PMINFO_R_OK) {
161 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
162 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
165 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
167 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
168 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
173 std::string getAppType(const std::string& pkgId)
179 pkgmgrinfo_pkginfo_h pkg_handle;
180 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
181 if (ret != PMINFO_R_OK) {
184 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
185 if (ret != PMINFO_R_OK) {
186 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
190 pkgmgrinfo_appinfo_h app_handle;
191 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
192 if (ret != PMINFO_R_OK) {
193 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
196 ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
197 if (ret != PMINFO_R_OK) {
198 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
199 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
204 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
205 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
210 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
214 std::string metadataValue;
216 pkgmgrinfo_pkginfo_h pkg_handle;
217 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
218 if (ret != PMINFO_R_OK) {
219 return metadataValue;
221 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
222 if (ret != PMINFO_R_OK) {
223 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
224 return metadataValue;
227 pkgmgrinfo_appinfo_h app_handle;
228 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
229 if (ret != PMINFO_R_OK) {
230 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
231 return metadataValue;
233 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
234 if (ret != PMINFO_R_OK) {
235 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
236 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
237 return metadataValue;
239 metadataValue = std::string(value);
241 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
242 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
244 return metadataValue;
247 std::string getBaseName(const std::string& path)
249 auto pos = path.find_last_of(PATH_SEPARATOR);
250 if (pos != std::string::npos)
251 return path.substr(0, pos);
253 return std::string(".");
257 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
259 std::string result = str;
260 std::string::size_type pos = 0;
261 std::string::size_type offset = 0;
263 while ((pos = result.find(pattern, offset)) != std::string::npos) {
264 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
265 offset = pos + replace.size();
271 bool isFile(const std::string& path)
274 return lstat(path.c_str(), &sb) == 0;
277 bool isDirectory(const std::string& path)
280 if (stat(path.c_str(), &sb) != 0) {
283 if (sb.st_mode & S_IFDIR) {
290 std::string getAssemblyNameFromPath(const std::string& path)
292 std::string ret(getFileName(path));
294 if (ret.find_last_of(".") == std::string::npos)
296 ret.erase(ret.find_last_of("."));
298 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
299 ret.erase(ret.size() - 3);
304 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
306 std::vector<std::string> assems;
307 std::unordered_map<std::string, std::string> assemPaths;
309 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
310 if (isManagedAssembly(filename) || isNativeImage(filename)) {
311 std::string assem = getAssemblyNameFromPath(filename);
313 if (assemPaths.count(assem) == 0) {
314 assems.push_back(assem);
315 assemPaths[assem] = path;
316 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
317 // Update only if a native image is found in the same directory.
318 // For example, if we have two directories = { X, Y } where X contains A.dll and
319 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
320 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
321 assemPaths[assem] = path;
325 for (auto& directory : directories)
326 scanFilesInDirectory(directory, reader, 0);
328 if (!list.empty() && list.back() != ':')
331 for (auto& assem : assems)
332 list += assemPaths[assem] + ":";
334 if (list.back() == ':')
338 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
341 struct dirent* entry;
344 dir = opendir(directory.c_str());
349 std::vector<std::string> innerDirectories;
351 while ((entry = readdir(dir)) != nullptr) {
353 std::string path = concatPath(directory, entry->d_name);
354 switch (entry->d_type) {
359 // symlink is added to the list even if there is no original file.
360 // It used to remove broken symlinks related to TAC
369 reader(path, entry->d_name);
370 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
371 innerDirectories.push_back(path);
375 for (auto& d : innerDirectories)
376 scanFilesInDirectory(d, reader, depth - 1);
381 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
387 // change smack label for symbolic link.
388 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
389 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
390 fprintf(stderr, "Fail to set smack label\n");
395 // change owner and groups for symbolic link.
396 if (!lstat(fromPath.c_str(), &info)) {
397 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
398 fprintf(stderr, "Failed to change owner and group name\n");
401 // change smack label
402 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
403 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
404 fprintf(stderr, "Fail to set smack label\n");
409 // change owner and groups for generated ni file.
410 if (!stat(fromPath.c_str(), &info)) {
411 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
412 fprintf(stderr, "Failed to change owner and group name\n");
417 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
419 int fd = open(path.c_str(), O_RDONLY);
421 _ERR("Can't open directory: %s", path.c_str());
424 int ret = fchown(fd, uid, gid);
427 _ERR("Failed to change owner of: %s", path.c_str());
433 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
435 bs::error_code error;
436 bf::permissions(path, permissions, error);
438 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
444 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
446 if (!setOwnership(path, uid, gid)) {
447 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
450 if (!setDirPermissions(path, permissions)) {
451 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
457 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
459 if (!bf::exists(path)) {
460 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
463 bf::perms permissions = bf::status(path).permissions();
465 if (stat(path.c_str(), &stats) != 0) {
468 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
469 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
475 bool createDir(const bf::path& path)
477 if (bf::exists(path)) {
480 bs::error_code error;
481 bf::create_directories(path, error);
483 _ERR("Failed to create directory: %s", error.message().c_str());
489 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
492 // Check whether the function call is valid
493 if (!bf::exists(path1) || !bf::is_directory(path1)) {
494 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
497 if (!bf::exists(path2)) {
498 // Create the destination directory
499 if (!createDir(path2)) {
500 _ERR("Unable to create destination directory %s", path2.c_str());
503 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
504 copyOwnershipAndPermissions(path1, path2);
507 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
508 _ERR("Destination directory %s already exists", path2.c_str());
511 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
512 copyOwnershipAndPermissions(path1, path2);
515 } catch (const bf::filesystem_error& error) {
516 _ERR("Failed to copy directory: %s", error.what());
520 // Iterate through the source directory
521 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
523 bf::path current(file->path());
524 bf::path target = path2 / current.filename();
525 if (bf::is_symlink(symlink_status(current))) {
526 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
529 bs::error_code error;
530 bf::copy_symlink(current, target, error);
532 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
535 } else if (bf::is_directory(current)) {
536 // Found directory: Recursion
537 if (!copyDir(current, target, flags)) {
541 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
544 bf::path destination = target;
545 if (flags & FS_COMMIT_COPY_FILE) {
546 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
548 if (flags & FS_MERGE_OVERWRITE) {
549 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
551 bf::copy_file(current, destination);
553 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
554 copyOwnershipAndPermissions(current, destination);
556 if (flags & FS_COMMIT_COPY_FILE) {
557 if (flags & FS_MERGE_OVERWRITE) {
560 bf::rename(destination, target);
563 } catch (const bf::filesystem_error& error) {
564 _ERR("Failed to copy directory: %s", error.what());
571 bool copyFile(const bf::path& path1, const bf::path& path2)
573 bs::error_code error;
574 if (!bf::exists(path1)) {
577 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
579 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
585 bool moveFile(const bf::path& path1, const bf::path& path2)
587 if (!bf::exists(path1) || bf::exists(path2)) {
590 bs::error_code error;
591 bf::rename(path1, path2, error);
593 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
594 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
596 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
599 bf::remove_all(path1, error);
601 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
608 bool removeFile(const bf::path& path)
610 if (!bf::exists(path)) {
613 bs::error_code error;
614 bf::remove(path, error);
616 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
622 bool removeAll(const bf::path& path)
627 bs::error_code error;
628 bf::remove_all(path, error);
630 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
636 void setCmdName(const std::string& name)
638 #define PRC_NAME_LENGTH 16
640 char processName[PRC_NAME_LENGTH] = {0, };
645 memset(processName, '\0', PRC_NAME_LENGTH);
646 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
647 prctl(PR_SET_NAME, processName);
650 std::string getFileName(const std::string& path)
652 std::string ret(path);
653 size_t index = ret.find_last_of(PATH_SEPARATOR);
654 return index == std::string::npos ? ret : ret.substr(index + 1);
657 std::string SHA256(const std::string& path)
659 std::string output = "";
660 FILE *file = fopen(path.c_str(), "rb");
665 unsigned char hash[SHA256_DIGEST_LENGTH];
667 SHA256_Init(&sha256);
669 const int bufSize = 32768;
670 char *buffer = (char*)malloc(bufSize);
676 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
677 SHA256_Update(&sha256, buffer, bytesRead);
679 SHA256_Final(hash, &sha256);
681 std::stringstream ss;
682 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
683 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];