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>
31 #include <unordered_map>
41 #include "path_manager.h"
43 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
45 return static_cast<int>(a.length()) - length >= aOffset &&
46 static_cast<int>(b.length()) - length >= bOffset &&
47 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
48 [](unsigned char a, unsigned char b)
49 { return std::tolower(a) == std::tolower(b); });
52 bool isManagedAssembly(const std::string& fileName)
54 return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
55 iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
56 !isNativeImage(fileName);
59 bool isNativeImage(const std::string& fileName)
61 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
64 std::string concatPath(const std::string& path1, const std::string& path2)
66 std::string path(path1);
67 if (path.back() == PATH_SEPARATOR) {
70 path += PATH_SEPARATOR;
77 void splitPath(const std::string& path, std::vector<std::string>& out)
79 std::istringstream ss(path);
82 while (std::getline(ss, token, ':')) {
87 std::string getAbsolutePath(const std::string& path)
90 char *realPath = realpath(path.c_str(), NULL);
92 absPath.assign(realPath);
99 std::string getRootPath(const std::string& pkgId)
103 std::string rootPath;
105 pkgmgrinfo_pkginfo_h pkg_handle;
106 ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
111 ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
112 if (ret != PMINFO_R_OK) {
113 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
117 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
122 std::string getExecName(const std::string& pkgId)
126 std::string execName;
128 pkgmgrinfo_pkginfo_h pkg_handle;
129 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
134 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
135 if (ret != PMINFO_R_OK) {
136 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
140 pkgmgrinfo_appinfo_h app_handle;
141 ret = pkgmgrGetAppInfo(appId, &app_handle);
143 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
147 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
148 if (ret != PMINFO_R_OK) {
149 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
150 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
153 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
155 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
156 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
161 std::string getAppType(const std::string& pkgId)
167 pkgmgrinfo_pkginfo_h pkg_handle;
168 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
173 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
174 if (ret != PMINFO_R_OK) {
175 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
179 pkgmgrinfo_appinfo_h app_handle;
180 ret = pkgmgrGetAppInfo(appId, &app_handle);
182 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
186 ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
187 if (ret != PMINFO_R_OK) {
188 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
189 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
194 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
195 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
200 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
204 std::string metadataValue;
206 pkgmgrinfo_pkginfo_h pkg_handle;
207 int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
209 return metadataValue;
212 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
213 if (ret != PMINFO_R_OK) {
214 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
215 return metadataValue;
218 pkgmgrinfo_appinfo_h app_handle;
219 ret = pkgmgrGetAppInfo(appId, &app_handle);
221 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
222 return metadataValue;
225 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
226 if (ret != PMINFO_R_OK) {
227 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
228 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
229 return metadataValue;
231 metadataValue = std::string(value);
233 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
234 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
236 return metadataValue;
239 bool isReadOnlyApp(const std::string& pkgId)
241 bool readOnly = false;
245 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
246 _ERR("Failed to get UID");
250 pkgmgrinfo_pkginfo_h handle;
252 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
254 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
257 if (ret != PMINFO_R_OK) {
261 ret = pkgmgrinfo_pkginfo_is_readonly(handle, &readOnly);
262 if (ret != PMINFO_R_OK) {
263 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
267 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
272 std::string getBaseName(const std::string& path)
274 auto pos = path.find_last_of(PATH_SEPARATOR);
275 if (pos != std::string::npos)
276 return path.substr(0, pos);
278 return std::string(".");
282 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
284 std::string result = str;
285 std::string::size_type pos = 0;
286 std::string::size_type offset = 0;
288 while ((pos = result.find(pattern, offset)) != std::string::npos) {
289 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
290 offset = pos + replace.size();
296 bool isFile(const std::string& path)
299 return lstat(path.c_str(), &sb) == 0;
302 bool isDirectory(const std::string& path)
305 if (stat(path.c_str(), &sb) != 0) {
308 if (sb.st_mode & S_IFDIR) {
315 std::string getAssemblyNameFromPath(const std::string& path)
317 std::string ret(getFileName(path));
319 if (ret.find_last_of(".") == std::string::npos)
321 ret.erase(ret.find_last_of("."));
323 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
324 ret.erase(ret.size() - 3);
329 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
331 std::vector<std::string> assems;
332 std::unordered_map<std::string, std::string> assemPaths;
334 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
335 if (isManagedAssembly(filename) || isNativeImage(filename)) {
336 std::string assem = getAssemblyNameFromPath(filename);
338 if (assemPaths.count(assem) == 0) {
339 assems.push_back(assem);
340 assemPaths[assem] = path;
341 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
342 // Update only if a native image is found in the same directory.
343 // For example, if we have two directories = { X, Y } where X contains A.dll and
344 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
345 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
346 assemPaths[assem] = path;
350 for (auto& directory : directories)
351 scanFilesInDirectory(directory, reader, 0);
353 if (!list.empty() && list.back() != ':')
356 for (auto& assem : assems)
357 list += assemPaths[assem] + ":";
359 if (list.back() == ':')
363 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
366 struct dirent* entry;
369 dir = opendir(directory.c_str());
374 std::vector<std::string> innerDirectories;
376 while ((entry = readdir(dir)) != nullptr) {
378 std::string path = concatPath(directory, entry->d_name);
379 switch (entry->d_type) {
384 // symlink is added to the list even if there is no original file.
385 // It used to remove broken symlinks related to TAC
394 reader(path, entry->d_name);
395 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
396 innerDirectories.push_back(path);
400 for (auto& d : innerDirectories)
401 scanFilesInDirectory(d, reader, depth - 1);
406 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
412 // change smack label for symbolic link.
413 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
414 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
415 fprintf(stderr, "Fail to set smack label\n");
420 // change owner and groups for symbolic link.
421 if (!lstat(fromPath.c_str(), &info)) {
422 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
423 fprintf(stderr, "Failed to change owner and group name\n");
426 // change smack label
427 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
428 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
429 fprintf(stderr, "Fail to set smack label\n");
434 // change owner and groups for generated ni file.
435 if (!stat(fromPath.c_str(), &info)) {
436 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
437 fprintf(stderr, "Failed to change owner and group name\n");
442 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
444 int fd = open(path.c_str(), O_RDONLY);
446 _ERR("Can't open directory: %s", path.c_str());
449 int ret = fchown(fd, uid, gid);
452 _ERR("Failed to change owner of: %s", path.c_str());
458 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
460 bs::error_code error;
461 bf::permissions(path, permissions, error);
463 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
469 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
471 if (!setOwnership(path, uid, gid)) {
472 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
475 if (!setDirPermissions(path, permissions)) {
476 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
482 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
485 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
488 bf::perms permissions = bf::status(path).permissions();
490 if (stat(path.c_str(), &stats) != 0) {
493 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
494 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
500 bool exist(const bf::path& path)
502 bs::error_code error;
503 int ret = bf::exists(path, error);
505 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
506 _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
512 bool createDir(const bf::path& path)
517 bs::error_code error;
518 bf::create_directories(path, error);
520 _ERR("Failed to create directory: %s", error.message().c_str());
526 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
529 // Check whether the function call is valid
530 if (!exist(path1) || !bf::is_directory(path1)) {
531 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
535 // Create the destination directory
536 if (!createDir(path2)) {
537 _ERR("Unable to create destination directory %s", path2.c_str());
540 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
541 copyOwnershipAndPermissions(path1, path2);
544 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
545 _ERR("Destination directory %s already exists", path2.c_str());
548 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
549 copyOwnershipAndPermissions(path1, path2);
552 } catch (const bf::filesystem_error& error) {
553 _ERR("Failed to copy directory: %s", error.what());
557 // Iterate through the source directory
558 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
560 bf::path current(file->path());
561 bf::path target = path2 / current.filename();
562 if (bf::is_symlink(symlink_status(current))) {
563 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
566 bs::error_code error;
567 bf::copy_symlink(current, target, error);
569 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
572 } else if (bf::is_directory(current)) {
573 // Found directory: Recursion
574 if (!copyDir(current, target, flags)) {
578 if ((flags & FS_MERGE_SKIP) && exist(target)) {
581 bf::path destination = target;
582 if (flags & FS_COMMIT_COPY_FILE) {
583 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
585 if (flags & FS_MERGE_OVERWRITE) {
586 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
588 bf::copy_file(current, destination);
590 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
591 copyOwnershipAndPermissions(current, destination);
593 if (flags & FS_COMMIT_COPY_FILE) {
594 if (flags & FS_MERGE_OVERWRITE) {
597 bf::rename(destination, target);
600 } catch (const bf::filesystem_error& error) {
601 _ERR("Failed to copy directory: %s", error.what());
608 bool copyFile(const bf::path& path1, const bf::path& path2)
610 bs::error_code error;
614 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
616 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
622 bool moveFile(const bf::path& path1, const bf::path& path2)
624 if (!exist(path1) || exist(path2)) {
627 bs::error_code error;
628 bf::rename(path1, path2, error);
630 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
631 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
633 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
636 bf::remove_all(path1, error);
638 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
645 bool removeFile(const bf::path& path)
650 bs::error_code error;
651 bf::remove(path, error);
653 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
659 bool removeAll(const bf::path& path)
664 bs::error_code error;
665 bf::remove_all(path, error);
667 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
673 void setCmdName(const std::string& name)
675 #define PRC_NAME_LENGTH 16
677 char processName[PRC_NAME_LENGTH] = {0, };
682 memset(processName, '\0', PRC_NAME_LENGTH);
683 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
684 prctl(PR_SET_NAME, processName);
687 std::string getFileName(const std::string& path)
689 std::string ret(path);
690 size_t index = ret.find_last_of(PATH_SEPARATOR);
691 return index == std::string::npos ? ret : ret.substr(index + 1);
694 std::string SHA256(const std::string& path)
696 std::string output = "";
697 FILE *file = fopen(path.c_str(), "rb");
702 unsigned char hash[SHA256_DIGEST_LENGTH];
704 SHA256_Init(&sha256);
706 const int bufSize = 32768;
707 char *buffer = (char*)malloc(bufSize);
713 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
714 SHA256_Update(&sha256, buffer, bytesRead);
716 SHA256_Final(hash, &sha256);
718 std::stringstream ss;
719 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
720 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
730 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
735 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
736 _ERR("Failed to get UID");
740 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
741 if (ret != PMINFO_R_OK) {
742 _ERR("Failed to get pkginfo (%d)", ret);
749 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
754 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
755 _ERR("Failed to get UID");
759 ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
760 if (ret != PMINFO_R_OK) {
761 _ERR("Failed to get appinfo (%d)", ret);
768 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
769 pkgmgrinfo_app_list_cb app_cb,
775 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
776 _ERR("Failed to get UID");
781 ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
782 if (ret != PMINFO_R_OK) {
783 _ERR("Failed to execute the metadata filter query (%d)", ret);