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 getAbsolutePath(const std::string& path)
106 char *realPath = realpath(path.c_str(), NULL);
108 absPath.assign(realPath);
115 int getRootPath(const 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(const 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(const std::string& pkgId, const 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 getBaseName(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 isFile(const std::string& path)
247 return stat(path.c_str(), &sb) == 0;
250 bool isDirectory(const std::string& path)
253 if (stat(path.c_str(), &sb) != 0) {
255 } else if (sb.st_mode & S_IFDIR) {
262 uintptr_t getFileSize(const std::string& path)
266 if (stat(path.c_str(), &sb) == 0) {
273 std::string getAssemblyNameFromPath(const std::string& path)
275 std::string ret(getFileName(path));
277 if (ret.find_last_of(".") == std::string::npos)
279 ret.erase(ret.find_last_of("."));
281 if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
282 ret.erase(ret.size() - 3);
287 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list) {
288 std::vector<std::string> assems;
289 std::unordered_map<std::string, std::string> assemPaths;
291 auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
292 if (isManagedAssembly(filename) || isNativeImage(filename)) {
293 std::string assem = getAssemblyNameFromPath(filename);
295 if (assemPaths.count(assem) == 0) {
296 assems.push_back(assem);
297 assemPaths[assem] = path;
298 } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
299 // Update only if a native image is found in the same directory.
300 // For example, if we have two directories = { X, Y } where X contains A.dll and
301 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
302 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
303 assemPaths[assem] = path;
307 for (auto& directory : directories)
308 scanFilesInDirectory(directory, reader, 0);
310 if (!list.empty() && list.back() != ':')
313 for (auto& assem : assems)
314 list += assemPaths[assem] + ":";
316 if (list.back() == ':')
320 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
323 struct dirent* entry;
326 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
329 dir = opendir(directory.c_str());
334 std::vector<std::string> innerDirectories;
336 while ((entry = readdir(dir)) != nullptr) {
338 std::string path = concatPath(directory, entry->d_name);
339 switch (entry->d_type) {
347 if (stat(path.c_str(), &sb) == -1)
350 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
356 reader(path, entry->d_name);
357 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
358 innerDirectories.push_back(path);
362 for (auto& d : innerDirectories)
363 scanFilesInDirectory(d, reader, depth - 1);
368 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
374 // change smack label for symbolic link.
375 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
376 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
377 fprintf(stderr, "Fail to set smack label\n");
382 // change owner and groups for symbolic link.
383 if (!stat(fromPath.c_str(), &info)) {
384 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
385 fprintf(stderr, "Failed to change owner and group name\n");
388 // change smack label
389 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
390 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
391 fprintf(stderr, "Fail to set smack label\n");
396 // change owner and groups for generated ni file.
397 if (!stat(fromPath.c_str(), &info)) {
398 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
399 fprintf(stderr, "Failed to change owner and group name\n");
404 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
405 int fd = open(path.c_str(), O_RDONLY);
407 _ERR("Can't open directory: %s", path.c_str());
410 int ret = fchown(fd, uid, gid);
413 _ERR("Failed to change owner of: %s", path.c_str());
419 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
420 bs::error_code error;
421 bf::permissions(path, permissions, error);
423 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
429 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
430 if (!setOwnership(path, uid, gid)) {
431 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
434 if (!setDirPermissions(path, permissions)) {
435 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
441 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
442 if (!bf::exists(path)) {
443 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
446 bf::perms permissions = bf::status(path).permissions();
448 if (stat(path.c_str(), &stats) != 0) {
451 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
452 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
458 bool createDir(const bf::path& path) {
459 if (bf::exists(path)) {
462 bs::error_code error;
463 bf::create_directories(path, error);
465 _ERR("Failed to create directory: %s", error.message().c_str());
471 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
473 // Check whether the function call is valid
474 if (!bf::exists(path1) || !bf::is_directory(path1)) {
475 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
478 if (!bf::exists(path2)) {
479 // Create the destination directory
480 if (!createDir(path2)) {
481 _ERR("Unable to create destination directory %s", path2.c_str());
484 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
485 copyOwnershipAndPermissions(path1, path2);
488 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
489 _ERR("Destination directory %s already exists", path2.c_str());
492 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
493 copyOwnershipAndPermissions(path1, path2);
496 } catch (const bf::filesystem_error& error) {
497 _ERR("Failed to copy directory: %s", error.what());
501 // Iterate through the source directory
502 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
504 bf::path current(file->path());
505 bf::path target = path2 / current.filename();
506 if (bf::is_symlink(symlink_status(current))) {
507 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
510 bs::error_code error;
511 bf::copy_symlink(current, target, error);
513 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
516 } else if (bf::is_directory(current)) {
517 // Found directory: Recursion
518 if (!copyDir(current, target, flags)) {
522 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
525 bf::path destination = target;
526 if (flags & FS_COMMIT_COPY_FILE) {
527 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
529 if (flags & FS_MERGE_OVERWRITE) {
530 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
532 bf::copy_file(current, destination);
534 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
535 copyOwnershipAndPermissions(current, destination);
537 if (flags & FS_COMMIT_COPY_FILE) {
538 if (flags & FS_MERGE_OVERWRITE) {
541 bf::rename(destination, target);
544 } catch (const bf::filesystem_error& error) {
545 _ERR("Failed to copy directory: %s", error.what());
552 bool copyFile(const bf::path& path1, const bf::path& path2) {
553 bs::error_code error;
554 if (!bf::exists(path1)) {
557 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
559 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
565 bool moveFile(const bf::path& path1, const bf::path& path2) {
566 if (!bf::exists(path1) || bf::exists(path2)) {
569 bs::error_code error;
570 bf::rename(path1, path2, error);
572 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
573 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
575 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
578 bf::remove_all(path1, error);
580 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
587 bool removeFile(const bf::path& path) {
588 if (!bf::exists(path)) {
591 bs::error_code error;
592 bf::remove(path, error);
594 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
600 bool removeAll(const bf::path& path) {
604 bs::error_code error;
605 bf::remove_all(path, error);
607 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
613 void setCmdName(const std::string& name)
615 #define PRC_NAME_LENGTH 16
617 char processName[PRC_NAME_LENGTH] = {0, };
622 memset(processName, '\0', PRC_NAME_LENGTH);
623 snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
624 prctl(PR_SET_NAME, processName);
627 std::string getFileName(const std::string& path)
629 std::string ret(path);
630 size_t index = ret.find_last_of(PATH_SEPARATOR);
631 return index == std::string::npos ? ret : ret.substr(index + 1);