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 = realpath(path.c_str(), NULL);
107 absPath.assign(realPath);
114 int getRootPath(std::string pkgId, std::string& rootPath)
120 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
121 _ERR("Failed to get UID");
125 pkgmgrinfo_pkginfo_h handle;
127 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
128 if (ret != PMINFO_R_OK) {
132 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
133 if (ret != PMINFO_R_OK) {
138 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
139 if (ret != PMINFO_R_OK) {
140 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
144 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
148 int getExecName(std::string pkgId, std::string& execName)
153 pkgmgrinfo_pkginfo_h pkg_handle;
154 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
155 if (ret != PMINFO_R_OK) {
158 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
159 if (ret != PMINFO_R_OK) {
160 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
164 pkgmgrinfo_appinfo_h app_handle;
165 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
166 if (ret != PMINFO_R_OK) {
167 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
170 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
171 if (ret != PMINFO_R_OK) {
172 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
173 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
176 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
178 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
179 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
183 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
188 pkgmgrinfo_pkginfo_h pkg_handle;
189 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
190 if (ret != PMINFO_R_OK) {
193 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
194 if (ret != PMINFO_R_OK) {
195 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
199 pkgmgrinfo_appinfo_h app_handle;
200 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
201 if (ret != PMINFO_R_OK) {
202 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
205 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
206 if (ret != PMINFO_R_OK) {
207 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
208 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
209 //Does not return error because the metadata key may not exist.
212 metadataValue = std::string(value);
214 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
215 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
219 std::string baseName(const std::string& path)
221 auto pos = path.find_last_of(PATH_SEPARATOR);
222 if (pos != std::string::npos)
223 return path.substr(0, pos);
225 return std::string(".");
229 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
231 std::string result = str;
232 std::string::size_type pos = 0;
233 std::string::size_type offset = 0;
235 while ((pos = result.find(pattern, offset)) != std::string::npos) {
236 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
237 offset = pos + replace.size();
243 bool isFileExist(const std::string& path)
246 return stat(path.c_str(), &sb) == 0;
249 uintptr_t getFileSize(const std::string& path)
253 if (stat(path.c_str(), &sb) == 0) {
260 std::string stripNiDLL(const std::string& path)
262 std::string niPath(path);
263 if (path.size() < 5) return niPath;
264 if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
265 niPath = path.substr(0, path.size()-4);
266 else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
267 niPath = path.substr(0, path.size()-4);
269 if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
270 return niPath.substr(0, niPath.size()-3);
275 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
277 std::map<std::string, std::string> assemblyList;
278 std::map<std::string, std::string> tmpList;
280 auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
281 if (isManagedAssembly(path) || isNativeImage(path)) {
282 std::string dllName = stripNiDLL(name);
283 std::pair<std::map<std::string, std::string>::iterator, bool> ret;
284 ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
285 if (ret.second == false) {
286 if (isNativeImage(path))
287 tmpList[dllName] = path;
292 for (auto directory : directories) {
293 scanFilesInDir(directory.c_str(), reader, 1);
294 // merge scaned dll list to tpa list.
295 // if the dll is already exist in the list, that is skipped.
296 assemblyList.insert(tmpList.begin(), tmpList.end());
299 std::map<std::string, std::string>::iterator it;
300 for (it = assemblyList.begin(); it != assemblyList.end(); it++)
301 tpaList += it->second + ':';
303 if (tpaList.back() == ':')
307 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
310 struct dirent* entry;
313 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
316 dir = opendir(directory.c_str());
321 std::vector<std::string> innerDirectories;
323 while ((entry = readdir(dir)) != nullptr) {
325 std::string path = concatPath(directory, entry->d_name);
326 switch (entry->d_type) {
334 if (stat(path.c_str(), &sb) == -1)
337 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
343 reader(path, entry->d_name);
344 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
345 innerDirectories.push_back(path);
349 for (auto& d : innerDirectories)
350 scanFilesInDir(d.c_str(), reader, depth - 1);
355 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
361 // change smack label for symbolic link.
362 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
363 if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
364 fprintf(stderr, "Fail to set smack label\n");
369 // change owner and groups for symbolic link.
370 if (!stat(fromPath.c_str(), &info)) {
371 if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
372 fprintf(stderr, "Failed to change owner and group name\n");
375 // change smack label
376 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
377 if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
378 fprintf(stderr, "Fail to set smack label\n");
383 // change owner and groups for generated ni file.
384 if (!stat(fromPath.c_str(), &info)) {
385 if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
386 fprintf(stderr, "Failed to change owner and group name\n");
391 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
392 int fd = open(path.c_str(), O_RDONLY);
394 _ERR("Can't open directory: %s", path.c_str());
397 int ret = fchown(fd, uid, gid);
400 _ERR("Failed to change owner of: %s", path.c_str());
406 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
407 bs::error_code error;
408 bf::permissions(path, permissions, error);
410 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
416 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
417 if (!setOwnership(path, uid, gid)) {
418 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
421 if (!setDirPermissions(path, permissions)) {
422 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
428 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
429 if (!bf::exists(path)) {
430 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
433 bf::perms permissions = bf::status(path).permissions();
435 if (stat(path.c_str(), &stats) != 0) {
438 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
439 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
445 bool createDir(const bf::path& path) {
446 if (bf::exists(path)) {
449 bs::error_code error;
450 bf::create_directories(path, error);
452 _ERR("Failed to create directory: %s", error.message().c_str());
458 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
460 // Check whether the function call is valid
461 if (!bf::exists(path1) || !bf::is_directory(path1)) {
462 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
465 if (!bf::exists(path2)) {
466 // Create the destination directory
467 if (!createDir(path2)) {
468 _ERR("Unable to create destination directory %s", path2.c_str());
471 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
472 copyOwnershipAndPermissions(path1, path2);
475 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
476 _ERR("Destination directory %s already exists", path2.c_str());
479 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
480 copyOwnershipAndPermissions(path1, path2);
483 } catch (const bf::filesystem_error& error) {
484 _ERR("Failed to copy directory: %s", error.what());
488 // Iterate through the source directory
489 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
491 bf::path current(file->path());
492 bf::path target = path2 / current.filename();
493 if (bf::is_symlink(symlink_status(current))) {
494 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
497 bs::error_code error;
498 bf::copy_symlink(current, target, error);
500 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
503 } else if (bf::is_directory(current)) {
504 // Found directory: Recursion
505 if (!copyDir(current, target, flags)) {
509 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
512 bf::path destination = target;
513 if (flags & FS_COMMIT_COPY_FILE) {
514 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
516 if (flags & FS_MERGE_OVERWRITE) {
517 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
519 bf::copy_file(current, destination);
521 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
522 copyOwnershipAndPermissions(current, destination);
524 if (flags & FS_COMMIT_COPY_FILE) {
525 if (flags & FS_MERGE_OVERWRITE) {
528 bf::rename(destination, target);
531 } catch (const bf::filesystem_error& error) {
532 _ERR("Failed to copy directory: %s", error.what());
539 bool copyFile(const bf::path& path1, const bf::path& path2) {
540 bs::error_code error;
541 if (!bf::exists(path1)) {
544 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
546 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
552 bool moveFile(const bf::path& path1, const bf::path& path2) {
553 if (!bf::exists(path1) || bf::exists(path2)) {
556 bs::error_code error;
557 bf::rename(path1, path2, error);
559 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
560 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
562 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
565 bf::remove_all(path1, error);
567 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
574 bool removeFile(const bf::path& path) {
575 if (!bf::exists(path)) {
578 bs::error_code error;
579 bf::remove(path, error);
581 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
587 bool removeAll(const bf::path& path) {
591 bs::error_code error;
592 bf::remove_all(path, error);
594 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());