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 <json/json.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[PATH_MAX];
107 if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
108 absPath.assign(realPath);
113 int getRootPath(std::string pkgId, std::string& rootPath)
119 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
120 _ERR("Failed to get UID");
124 pkgmgrinfo_pkginfo_h handle;
126 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
127 if (ret != PMINFO_R_OK) {
131 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
132 if (ret != PMINFO_R_OK) {
137 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
138 if (ret != PMINFO_R_OK) {
139 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
143 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
147 int getExecName(std::string pkgId, std::string& execName)
152 pkgmgrinfo_pkginfo_h pkg_handle;
153 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
154 if (ret != PMINFO_R_OK) {
157 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
158 if (ret != PMINFO_R_OK) {
159 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
163 pkgmgrinfo_appinfo_h app_handle;
164 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
165 if (ret != PMINFO_R_OK) {
166 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
169 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
170 if (ret != PMINFO_R_OK) {
171 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
172 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
175 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
177 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
178 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
182 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
187 pkgmgrinfo_pkginfo_h pkg_handle;
188 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
189 if (ret != PMINFO_R_OK) {
192 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
193 if (ret != PMINFO_R_OK) {
194 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
198 pkgmgrinfo_appinfo_h app_handle;
199 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
200 if (ret != PMINFO_R_OK) {
201 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
204 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
205 if (ret != PMINFO_R_OK) {
206 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
207 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
208 //Does not return error because the metadata key may not exist.
211 metadataValue = std::string(value);
213 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
214 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
218 std::string baseName(const std::string& path)
220 auto pos = path.find_last_of(PATH_SEPARATOR);
221 if (pos != std::string::npos)
222 return path.substr(0, pos);
224 return std::string(".");
228 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
230 std::string result = str;
231 std::string::size_type pos = 0;
232 std::string::size_type offset = 0;
234 while ((pos = result.find(pattern, offset)) != std::string::npos) {
235 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
236 offset = pos + replace.size();
242 bool isFileExist(const std::string& path)
245 return stat(path.c_str(), &sb) == 0;
248 uintptr_t getFileSize(const std::string& path)
252 if (stat(path.c_str(), &sb) == 0) {
259 std::string stripNiDLL(const std::string& path)
261 std::string niPath(path);
262 if (path.size() < 5) return niPath;
263 if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
264 niPath = path.substr(0, path.size()-4);
265 else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
266 niPath = path.substr(0, path.size()-4);
268 if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
269 return niPath.substr(0, niPath.size()-3);
274 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
276 std::map<std::string, std::string> assemblyList;
277 std::map<std::string, std::string> tmpList;
279 auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
280 if (isManagedAssembly(path) || isNativeImage(path)) {
281 std::string dllName = stripNiDLL(name);
282 std::pair<std::map<std::string, std::string>::iterator, bool> ret;
283 ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
284 if (ret.second == false) {
285 if (isNativeImage(path))
286 tmpList[dllName] = path;
291 for (auto directory : directories) {
292 scanFilesInDir(directory.c_str(), reader, 1);
293 // merge scaned dll list to tpa list.
294 // if the dll is already exist in the list, that is skipped.
295 assemblyList.insert(tmpList.begin(), tmpList.end());
298 std::map<std::string, std::string>::iterator it;
299 for (it = assemblyList.begin(); it != assemblyList.end(); it++)
300 tpaList += it->second + ':';
302 if (tpaList.back() == ':')
306 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
309 struct dirent* entry;
312 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
315 dir = opendir(directory.c_str());
320 std::vector<std::string> innerDirectories;
322 while ((entry = readdir(dir)) != nullptr) {
324 std::string path = concatPath(directory, entry->d_name);
325 switch (entry->d_type) {
333 if (stat(path.c_str(), &sb) == -1)
336 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
342 reader(path, entry->d_name);
343 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
344 innerDirectories.push_back(path);
348 for (auto& d : innerDirectories)
349 scanFilesInDir(d.c_str(), reader, depth - 1);
354 void updateAssemblyInfo(const std::string& getPath, const std::string& setPath, bool isSymlink)
360 // change smack label for symbolic link.
361 if (smack_lgetlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
362 if (smack_lsetlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
363 fprintf(stderr, "Fail to set smack label\n");
368 // change owner and groups for symbolic link.
369 if (!stat(getPath.c_str(), &info)) {
370 if (lchown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
371 fprintf(stderr, "Failed to change owner and group name\n");
374 // change smack label
375 if (smack_getlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
376 if (smack_setlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
377 fprintf(stderr, "Fail to set smack label\n");
382 // change owner and groups for generated ni file.
383 if (!stat(getPath.c_str(), &info)) {
384 if (chown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
385 fprintf(stderr, "Failed to change owner and group name\n");
390 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
391 int fd = open(path.c_str(), O_RDONLY);
393 _ERR("Can't open directory: %s", path.c_str());
396 int ret = fchown(fd, uid, gid);
399 _ERR("Failed to change owner of: %s", path.c_str());
405 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
406 bs::error_code error;
407 bf::permissions(path, permissions, error);
409 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
415 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
416 if (!setOwnership(path, uid, gid)) {
417 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
420 if (!setDirPermissions(path, permissions)) {
421 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
427 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
428 if (!bf::exists(path)) {
429 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
432 bf::perms permissions = bf::status(path).permissions();
434 if (stat(path.c_str(), &stats) != 0) {
437 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
438 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
444 bool createDir(const bf::path& path) {
445 if (bf::exists(path)) {
448 bs::error_code error;
449 bf::create_directories(path, error);
451 _ERR("Failed to create directory: %s", error.message().c_str());
457 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
459 // Check whether the function call is valid
460 if (!bf::exists(path1) || !bf::is_directory(path1)) {
461 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
464 if (!bf::exists(path2)) {
465 // Create the destination directory
466 if (!createDir(path2)) {
467 _ERR("Unable to create destination directory %s", path2.c_str());
470 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
471 copyOwnershipAndPermissions(path1, path2);
474 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
475 _ERR("Destination directory %s already exists", path2.c_str());
478 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
479 copyOwnershipAndPermissions(path1, path2);
482 } catch (const bf::filesystem_error& error) {
483 _ERR("Failed to copy directory: %s", error.what());
487 // Iterate through the source directory
488 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
490 bf::path current(file->path());
491 bf::path target = path2 / current.filename();
492 if (bf::is_symlink(symlink_status(current))) {
493 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
496 bs::error_code error;
497 bf::copy_symlink(current, target, error);
499 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
502 } else if (bf::is_directory(current)) {
503 // Found directory: Recursion
504 if (!copyDir(current, target, flags)) {
508 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
511 bf::path destination = target;
512 if (flags & FS_COMMIT_COPY_FILE) {
513 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
515 if (flags & FS_MERGE_OVERWRITE) {
516 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
518 bf::copy_file(current, destination);
520 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
521 copyOwnershipAndPermissions(current, destination);
523 if (flags & FS_COMMIT_COPY_FILE) {
524 if (flags & FS_MERGE_OVERWRITE) {
527 bf::rename(destination, target);
530 } catch (const bf::filesystem_error& error) {
531 _ERR("Failed to copy directory: %s", error.what());
538 bool copyFile(const bf::path& path1, const bf::path& path2) {
539 bs::error_code error;
540 if (!bf::exists(path1)) {
543 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
545 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
551 bool moveFile(const bf::path& path1, const bf::path& path2) {
552 if (!bf::exists(path1) || bf::exists(path2)) {
555 bs::error_code error;
556 bf::rename(path1, path2, error);
558 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
559 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
561 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
564 bf::remove_all(path1, error);
566 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
573 bool removeFile(const bf::path& path) {
574 if (!bf::exists(path)) {
577 bs::error_code error;
578 bf::remove(path, error);
580 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
586 bool removeAll(const bf::path& path) {
590 bs::error_code error;
591 bf::remove_all(path, error);
593 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
599 //Parser the .deps.json file to get nuget information.
600 std::vector<std::string> depsJsonParser(std::string rootPath, std::string execName, std::string tpaList)
602 std::vector<std::string> tpaAssemblies;
603 splitPath(tpaList, tpaAssemblies);
605 std::vector<std::string> parserData;
606 std::string depsJsonName = execName.substr(0, execName.rfind(".dll")) + ".deps.json";
607 std::string depsJsonPath = concatPath(rootPath, depsJsonName);
608 if (bf::exists(depsJsonPath)) {
609 std::ifstream ifs(depsJsonPath);
610 Json::CharReaderBuilder reader;
614 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
615 _ERR("Failed to parse of deps.json");
617 tpaAssemblies.clear();
620 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
621 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
622 std::vector<std::string> appDependencies;
623 for (auto& nuget : nugetPackages.getMemberNames()) {
624 if (strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) != NULL ||
625 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) != NULL) {
626 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
627 if (assemblies != Json::nullValue) {
628 const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
629 for (auto& dependency : dependencies.getMemberNames()) {
630 appDependencies.push_back(dependency);
635 for (auto& nuget : nugetPackages.getMemberNames()) {
636 //Skip the nuget package related to Tizen
637 if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
638 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) == NULL &&
639 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) == NULL &&
640 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) == NULL) {
641 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
642 if (assemblies != Json::nullValue) {
643 const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
644 bool hasDependency = false;
645 for (auto& dependency : dependencies.getMemberNames()) {
646 //Skip the nugget package that is dependent on another nuget package
647 if (strstr(dependency.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
648 strstr(dependency.c_str(), NET_STANDARD_LIBRARY_NUGET) == NULL) {
649 hasDependency = true;
650 for (auto& ad : appDependencies) {
651 if (!strcmp(ad.c_str(), dependency.c_str())) {
652 hasDependency = true;
655 hasDependency = false;
660 if (!hasDependency) {
661 bool isExistTpaAssembly = false;
662 for (auto& assembly : assemblies.getMemberNames()) {
663 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
664 //Skip the assembly present in the TPA list
665 for (auto& tpa : tpaAssemblies) {
666 if (!strcmp(replaceAll(tpa, ".ni.dll", ".dll").c_str(), assembly.c_str())) {
667 isExistTpaAssembly = true;
671 if (isExistTpaAssembly) break;
673 if (!isExistTpaAssembly) {
674 for (auto& assembly : assemblies.getMemberNames()) {
675 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
676 parserData.push_back(nuget + ":" + assemblyName);
677 _INFO("Nuget : [%s] / Assembly : [%s]", nuget.c_str(), assemblyName.c_str());
684 appDependencies.clear();
688 tpaAssemblies.clear();