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)
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 exist(const bf::path& path)
477 bs::error_code error;
478 int ret = bf::exists(path, error);
480 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
481 _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
487 bool createDir(const bf::path& path)
492 bs::error_code error;
493 bf::create_directories(path, error);
495 _ERR("Failed to create directory: %s", error.message().c_str());
501 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
504 // Check whether the function call is valid
505 if (!exist(path1) || !bf::is_directory(path1)) {
506 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
510 // Create the destination directory
511 if (!createDir(path2)) {
512 _ERR("Unable to create destination directory %s", path2.c_str());
515 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
516 copyOwnershipAndPermissions(path1, path2);
519 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
520 _ERR("Destination directory %s already exists", path2.c_str());
523 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
524 copyOwnershipAndPermissions(path1, path2);
527 } catch (const bf::filesystem_error& error) {
528 _ERR("Failed to copy directory: %s", error.what());
532 // Iterate through the source directory
533 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
535 bf::path current(file->path());
536 bf::path target = path2 / current.filename();
537 if (bf::is_symlink(symlink_status(current))) {
538 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
541 bs::error_code error;
542 bf::copy_symlink(current, target, error);
544 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
547 } else if (bf::is_directory(current)) {
548 // Found directory: Recursion
549 if (!copyDir(current, target, flags)) {
553 if ((flags & FS_MERGE_SKIP) && exist(target)) {
556 bf::path destination = target;
557 if (flags & FS_COMMIT_COPY_FILE) {
558 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
560 if (flags & FS_MERGE_OVERWRITE) {
561 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
563 bf::copy_file(current, destination);
565 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
566 copyOwnershipAndPermissions(current, destination);
568 if (flags & FS_COMMIT_COPY_FILE) {
569 if (flags & FS_MERGE_OVERWRITE) {
572 bf::rename(destination, target);
575 } catch (const bf::filesystem_error& error) {
576 _ERR("Failed to copy directory: %s", error.what());
583 bool copyFile(const bf::path& path1, const bf::path& path2)
585 bs::error_code error;
589 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
591 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
597 bool moveFile(const bf::path& path1, const bf::path& path2)
599 if (!exist(path1) || exist(path2)) {
602 bs::error_code error;
603 bf::rename(path1, path2, error);
605 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
606 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
608 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
611 bf::remove_all(path1, error);
613 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
620 bool removeFile(const bf::path& path)
625 bs::error_code error;
626 bf::remove(path, error);
628 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
634 bool removeAll(const bf::path& path)
639 bs::error_code error;
640 bf::remove_all(path, error);
642 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
648 void setCmdName(const std::string& name)
650 #define PRC_NAME_LENGTH 16
652 char processName[PRC_NAME_LENGTH] = {0, };
657 memset(processName, '\0', PRC_NAME_LENGTH);
658 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
659 prctl(PR_SET_NAME, processName);
662 std::string getFileName(const std::string& path)
664 std::string ret(path);
665 size_t index = ret.find_last_of(PATH_SEPARATOR);
666 return index == std::string::npos ? ret : ret.substr(index + 1);
669 std::string SHA256(const std::string& path)
671 std::string output = "";
672 FILE *file = fopen(path.c_str(), "rb");
677 unsigned char hash[SHA256_DIGEST_LENGTH];
679 SHA256_Init(&sha256);
681 const int bufSize = 32768;
682 char *buffer = (char*)malloc(bufSize);
688 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
689 SHA256_Update(&sha256, buffer, bytesRead);
691 SHA256_Final(hash, &sha256);
693 std::stringstream ss;
694 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
695 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];