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>
30 #include <unordered_map>
39 #include "path_manager.h"
41 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
43 return static_cast<int>(a.length()) - length >= aOffset &&
44 static_cast<int>(b.length()) - length >= bOffset &&
45 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
46 [](unsigned char a, unsigned char b)
47 { return std::tolower(a) == std::tolower(b); });
50 bool isManagedAssembly(const std::string& fileName)
52 return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
53 iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
54 !isNativeImage(fileName);
57 bool isNativeImage(const std::string& fileName)
59 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
62 bool cmdOptionExists(char** begin, char** end, const std::string& option)
64 return std::find(begin, end, option) != end;
67 std::string readSelfPath()
70 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
73 return std::string(buff);
79 std::string concatPath(const std::string& path1, const std::string& path2)
81 std::string path(path1);
82 if (path.back() == PATH_SEPARATOR) {
85 path += PATH_SEPARATOR;
92 void splitPath(const std::string& path, std::vector<std::string>& out)
94 std::istringstream ss(path);
97 while (std::getline(ss, token, ':')) {
102 std::string absolutePath(const std::string& path)
105 char realPath[PATH_MAX];
106 if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
107 absPath.assign(realPath);
112 int getRootPath(std::string pkgId, std::string& rootPath)
118 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
119 _ERR("Failed to get UID");
123 pkgmgrinfo_pkginfo_h handle;
125 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
126 if (ret != PMINFO_R_OK) {
130 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
131 if (ret != PMINFO_R_OK) {
136 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
137 if (ret != PMINFO_R_OK) {
138 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
142 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
146 int getExecName(std::string pkgId, std::string& execName)
151 pkgmgrinfo_pkginfo_h pkg_handle;
152 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
153 if (ret != PMINFO_R_OK) {
156 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
157 if (ret != PMINFO_R_OK) {
158 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
162 pkgmgrinfo_appinfo_h app_handle;
163 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
164 if (ret != PMINFO_R_OK) {
165 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
168 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
169 if (ret != PMINFO_R_OK) {
170 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
171 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
174 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
176 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
177 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
181 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
186 pkgmgrinfo_pkginfo_h pkg_handle;
187 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
188 if (ret != PMINFO_R_OK) {
191 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
192 if (ret != PMINFO_R_OK) {
193 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
197 pkgmgrinfo_appinfo_h app_handle;
198 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
199 if (ret != PMINFO_R_OK) {
200 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
203 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
204 if (ret != PMINFO_R_OK) {
205 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
206 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
207 //Does not return error because the metadata key may not exist.
210 metadataValue = std::string(value);
212 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
213 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
217 std::string baseName(const std::string& path)
219 auto pos = path.find_last_of(PATH_SEPARATOR);
220 if (pos != std::string::npos)
221 return path.substr(0, pos);
223 return std::string(".");
227 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
229 std::string result = str;
230 std::string::size_type pos = 0;
231 std::string::size_type offset = 0;
233 while ((pos = result.find(pattern, offset)) != std::string::npos) {
234 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
235 offset = pos + replace.size();
241 bool isFileExist(const std::string& path)
244 return stat(path.c_str(), &sb) == 0;
247 uintptr_t getFileSize(const std::string& path)
251 if (stat(path.c_str(), &sb) == 0) {
258 std::string stripNiDLL(const std::string& path)
260 std::string niPath(path);
261 if (path.size() < 5) return niPath;
262 if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
263 niPath = path.substr(0, path.size()-4);
264 else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
265 niPath = path.substr(0, path.size()-4);
267 if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
268 return niPath.substr(0, niPath.size()-3);
273 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
275 std::map<std::string, std::string> assemblyList;
276 std::map<std::string, std::string> tmpList;
278 auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
279 if (isManagedAssembly(path) || isNativeImage(path)) {
280 std::string dllName = stripNiDLL(name);
281 std::pair<std::map<std::string, std::string>::iterator, bool> ret;
282 ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
283 if (ret.second == false) {
284 if (isNativeImage(path))
285 tmpList[dllName] = path;
290 for (auto directory : directories) {
291 scanFilesInDir(directory.c_str(), reader, 1);
292 // merge scaned dll list to tpa list.
293 // if the dll is already exist in the list, that is skipped.
294 assemblyList.insert(tmpList.begin(), tmpList.end());
297 std::map<std::string, std::string>::iterator it;
298 for (it = assemblyList.begin(); it != assemblyList.end(); it++)
299 tpaList += it->second + ':';
301 if (tpaList.back() == ':')
305 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
308 struct dirent* entry;
311 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
314 dir = opendir(directory.c_str());
319 std::vector<std::string> innerDirectories;
321 while ((entry = readdir(dir)) != nullptr) {
323 std::string path = concatPath(directory, entry->d_name);
324 switch (entry->d_type) {
332 if (stat(path.c_str(), &sb) == -1)
335 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
341 reader(path, entry->d_name);
342 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
343 innerDirectories.push_back(path);
347 for (auto& d : innerDirectories)
348 scanFilesInDir(d.c_str(), reader, depth - 1);
353 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
359 // change smack label for symbolic link.
360 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
361 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
362 fprintf(stderr, "Fail to set smack label\n");
367 // change owner and groups for symbolic link.
368 if (!stat(fromPath.c_str(), &info)) {
369 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
370 fprintf(stderr, "Failed to change owner and group name\n");
373 // change smack label
374 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
375 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
376 fprintf(stderr, "Fail to set smack label\n");
381 // change owner and groups for generated ni file.
382 if (!stat(fromPath.c_str(), &info)) {
383 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
384 fprintf(stderr, "Failed to change owner and group name\n");
389 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
390 int fd = open(path.c_str(), O_RDONLY);
392 _ERR("Can't open directory: %s", path.c_str());
395 int ret = fchown(fd, uid, gid);
398 _ERR("Failed to change owner of: %s", path.c_str());
404 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
405 bs::error_code error;
406 bf::permissions(path, permissions, error);
408 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
414 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
415 if (!setOwnership(path, uid, gid)) {
416 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
419 if (!setDirPermissions(path, permissions)) {
420 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
426 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
427 if (!bf::exists(path)) {
428 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
431 bf::perms permissions = bf::status(path).permissions();
433 if (stat(path.c_str(), &stats) != 0) {
436 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
437 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
443 bool createDir(const bf::path& path) {
444 if (bf::exists(path)) {
447 bs::error_code error;
448 bf::create_directories(path, error);
450 _ERR("Failed to create directory: %s", error.message().c_str());
456 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
458 // Check whether the function call is valid
459 if (!bf::exists(path1) || !bf::is_directory(path1)) {
460 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
463 if (!bf::exists(path2)) {
464 // Create the destination directory
465 if (!createDir(path2)) {
466 _ERR("Unable to create destination directory %s", path2.c_str());
469 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
470 copyOwnershipAndPermissions(path1, path2);
473 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
474 _ERR("Destination directory %s already exists", path2.c_str());
477 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
478 copyOwnershipAndPermissions(path1, path2);
481 } catch (const bf::filesystem_error& error) {
482 _ERR("Failed to copy directory: %s", error.what());
486 // Iterate through the source directory
487 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
489 bf::path current(file->path());
490 bf::path target = path2 / current.filename();
491 if (bf::is_symlink(symlink_status(current))) {
492 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
495 bs::error_code error;
496 bf::copy_symlink(current, target, error);
498 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
501 } else if (bf::is_directory(current)) {
502 // Found directory: Recursion
503 if (!copyDir(current, target, flags)) {
507 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
510 bf::path destination = target;
511 if (flags & FS_COMMIT_COPY_FILE) {
512 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
514 if (flags & FS_MERGE_OVERWRITE) {
515 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
517 bf::copy_file(current, destination);
519 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
520 copyOwnershipAndPermissions(current, destination);
522 if (flags & FS_COMMIT_COPY_FILE) {
523 if (flags & FS_MERGE_OVERWRITE) {
526 bf::rename(destination, target);
529 } catch (const bf::filesystem_error& error) {
530 _ERR("Failed to copy directory: %s", error.what());
537 bool copyFile(const bf::path& path1, const bf::path& path2) {
538 bs::error_code error;
539 if (!bf::exists(path1)) {
542 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
544 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
550 bool moveFile(const bf::path& path1, const bf::path& path2) {
551 if (!bf::exists(path1) || bf::exists(path2)) {
554 bs::error_code error;
555 bf::rename(path1, path2, error);
557 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
558 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
560 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
563 bf::remove_all(path1, error);
565 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
572 bool removeFile(const bf::path& path) {
573 if (!bf::exists(path)) {
576 bs::error_code error;
577 bf::remove(path, error);
579 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
585 bool removeAll(const bf::path& path) {
589 bs::error_code error;
590 bf::remove_all(path, error);
592 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());