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>
31 #include <unordered_map>
40 #include "path_manager.h"
42 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
44 return static_cast<int>(a.length()) - length >= aOffset &&
45 static_cast<int>(b.length()) - length >= bOffset &&
46 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
47 [](unsigned char a, unsigned char b)
48 { return std::tolower(a) == std::tolower(b); });
51 bool isManagedAssembly(const std::string& fileName)
53 return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
54 iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
55 !isNativeImage(fileName);
58 bool isNativeImage(const std::string& fileName)
60 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
63 bool cmdOptionExists(char** begin, char** end, const std::string& option)
65 return std::find(begin, end, option) != end;
68 std::string readSelfPath()
71 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
74 return std::string(buff);
80 std::string concatPath(const std::string& path1, const std::string& path2)
82 std::string path(path1);
83 if (path.back() == PATH_SEPARATOR) {
86 path += PATH_SEPARATOR;
93 void splitPath(const std::string& path, std::vector<std::string>& out)
95 std::istringstream ss(path);
98 while (std::getline(ss, token, ':')) {
103 std::string absolutePath(const std::string& path)
106 char *realPath = realpath(path.c_str(), NULL);
108 absPath.assign(realPath);
115 int getRootPath(std::string pkgId, std::string& rootPath)
121 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
122 _ERR("Failed to get UID");
126 pkgmgrinfo_pkginfo_h handle;
128 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
129 if (ret != PMINFO_R_OK) {
133 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
134 if (ret != PMINFO_R_OK) {
139 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
140 if (ret != PMINFO_R_OK) {
141 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
145 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
149 int getExecName(std::string pkgId, std::string& execName)
154 pkgmgrinfo_pkginfo_h pkg_handle;
155 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
156 if (ret != PMINFO_R_OK) {
159 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
160 if (ret != PMINFO_R_OK) {
161 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
165 pkgmgrinfo_appinfo_h app_handle;
166 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
167 if (ret != PMINFO_R_OK) {
168 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
171 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
172 if (ret != PMINFO_R_OK) {
173 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
174 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
177 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
179 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
180 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
184 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
189 pkgmgrinfo_pkginfo_h pkg_handle;
190 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
191 if (ret != PMINFO_R_OK) {
194 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
195 if (ret != PMINFO_R_OK) {
196 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
200 pkgmgrinfo_appinfo_h app_handle;
201 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
202 if (ret != PMINFO_R_OK) {
203 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
206 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
207 if (ret != PMINFO_R_OK) {
208 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
209 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
210 //Does not return error because the metadata key may not exist.
213 metadataValue = std::string(value);
215 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
216 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
220 std::string baseName(const std::string& path)
222 auto pos = path.find_last_of(PATH_SEPARATOR);
223 if (pos != std::string::npos)
224 return path.substr(0, pos);
226 return std::string(".");
230 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
232 std::string result = str;
233 std::string::size_type pos = 0;
234 std::string::size_type offset = 0;
236 while ((pos = result.find(pattern, offset)) != std::string::npos) {
237 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
238 offset = pos + replace.size();
244 bool isFileExist(const std::string& path)
247 return stat(path.c_str(), &sb) == 0;
250 uintptr_t getFileSize(const std::string& path)
254 if (stat(path.c_str(), &sb) == 0) {
261 std::string getAssemblyNameFromPath(const std::string& path)
263 std::string ret(getFileName(path));
265 if (ret.find_last_of(".") == std::string::npos)
267 ret.erase(ret.find_last_of("."));
269 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
270 ret.erase(ret.size() - 3);
275 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list) {
276 std::vector<std::string> assems;
277 std::unordered_map<std::string, std::string> assemPaths;
279 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
280 if (isManagedAssembly(filename) || isNativeImage(filename)) {
281 std::string assem = getAssemblyNameFromPath(filename);
283 if (assemPaths.count(assem) == 0) {
284 assems.push_back(assem);
285 assemPaths[assem] = path;
286 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
287 // Update only if a native image is found in the same directory.
288 // For example, if we have two directories = { X, Y } where X contains A.dll and
289 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
290 if (baseName(assemPaths[assem]).compare(baseName(path)) == 0)
291 assemPaths[assem] = path;
295 for (auto& directory : directories)
296 scanFilesInDirectory(directory, reader, 0);
298 if (!list.empty() && list.back() != ':')
301 for (auto& assem : assems)
302 list += assemPaths[assem] + ":";
304 if (list.back() == ':')
308 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
311 struct dirent* entry;
314 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
317 dir = opendir(directory.c_str());
322 std::vector<std::string> innerDirectories;
324 while ((entry = readdir(dir)) != nullptr) {
326 std::string path = concatPath(directory, entry->d_name);
327 switch (entry->d_type) {
335 if (stat(path.c_str(), &sb) == -1)
338 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
344 reader(path, entry->d_name);
345 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
346 innerDirectories.push_back(path);
350 for (auto& d : innerDirectories)
351 scanFilesInDirectory(d, reader, depth - 1);
356 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
362 // change smack label for symbolic link.
363 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
364 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
365 fprintf(stderr, "Fail to set smack label\n");
370 // change owner and groups for symbolic link.
371 if (!stat(fromPath.c_str(), &info)) {
372 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
373 fprintf(stderr, "Failed to change owner and group name\n");
376 // change smack label
377 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
378 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
379 fprintf(stderr, "Fail to set smack label\n");
384 // change owner and groups for generated ni file.
385 if (!stat(fromPath.c_str(), &info)) {
386 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
387 fprintf(stderr, "Failed to change owner and group name\n");
392 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
393 int fd = open(path.c_str(), O_RDONLY);
395 _ERR("Can't open directory: %s", path.c_str());
398 int ret = fchown(fd, uid, gid);
401 _ERR("Failed to change owner of: %s", path.c_str());
407 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
408 bs::error_code error;
409 bf::permissions(path, permissions, error);
411 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
417 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
418 if (!setOwnership(path, uid, gid)) {
419 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
422 if (!setDirPermissions(path, permissions)) {
423 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
429 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
430 if (!bf::exists(path)) {
431 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
434 bf::perms permissions = bf::status(path).permissions();
436 if (stat(path.c_str(), &stats) != 0) {
439 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
440 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
446 bool createDir(const bf::path& path) {
447 if (bf::exists(path)) {
450 bs::error_code error;
451 bf::create_directories(path, error);
453 _ERR("Failed to create directory: %s", error.message().c_str());
459 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
461 // Check whether the function call is valid
462 if (!bf::exists(path1) || !bf::is_directory(path1)) {
463 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
466 if (!bf::exists(path2)) {
467 // Create the destination directory
468 if (!createDir(path2)) {
469 _ERR("Unable to create destination directory %s", path2.c_str());
472 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
473 copyOwnershipAndPermissions(path1, path2);
476 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
477 _ERR("Destination directory %s already exists", path2.c_str());
480 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
481 copyOwnershipAndPermissions(path1, path2);
484 } catch (const bf::filesystem_error& error) {
485 _ERR("Failed to copy directory: %s", error.what());
489 // Iterate through the source directory
490 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
492 bf::path current(file->path());
493 bf::path target = path2 / current.filename();
494 if (bf::is_symlink(symlink_status(current))) {
495 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
498 bs::error_code error;
499 bf::copy_symlink(current, target, error);
501 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
504 } else if (bf::is_directory(current)) {
505 // Found directory: Recursion
506 if (!copyDir(current, target, flags)) {
510 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
513 bf::path destination = target;
514 if (flags & FS_COMMIT_COPY_FILE) {
515 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
517 if (flags & FS_MERGE_OVERWRITE) {
518 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
520 bf::copy_file(current, destination);
522 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
523 copyOwnershipAndPermissions(current, destination);
525 if (flags & FS_COMMIT_COPY_FILE) {
526 if (flags & FS_MERGE_OVERWRITE) {
529 bf::rename(destination, target);
532 } catch (const bf::filesystem_error& error) {
533 _ERR("Failed to copy directory: %s", error.what());
540 bool copyFile(const bf::path& path1, const bf::path& path2) {
541 bs::error_code error;
542 if (!bf::exists(path1)) {
545 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
547 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
553 bool moveFile(const bf::path& path1, const bf::path& path2) {
554 if (!bf::exists(path1) || bf::exists(path2)) {
557 bs::error_code error;
558 bf::rename(path1, path2, error);
560 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
561 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
563 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
566 bf::remove_all(path1, error);
568 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
575 bool removeFile(const bf::path& path) {
576 if (!bf::exists(path)) {
579 bs::error_code error;
580 bf::remove(path, error);
582 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
588 bool removeAll(const bf::path& path) {
592 bs::error_code error;
593 bf::remove_all(path, error);
595 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
601 void setCmdName(const std::string& name)
603 #define PRC_NAME_LENGTH 16
605 char processName[PRC_NAME_LENGTH] = {0, };
610 memset(processName, '\0', PRC_NAME_LENGTH);
611 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
612 prctl(PR_SET_NAME, processName);
615 std::string getFileName(const std::string& path)
617 std::string ret(path);
618 size_t index = ret.find_last_of(PATH_SEPARATOR);
619 return index == std::string::npos ? ret : ret.substr(index + 1);