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>
27 #include <openssl/sha.h>
32 #include <unordered_map>
40 #include "path_manager.h"
41 #include "db_manager.h"
44 #define __STR(x) __XSTR(x)
45 static const char* __TAC_DIR = __STR(TAC_DIR);
49 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
51 return static_cast<int>(a.length()) - length >= aOffset &&
52 static_cast<int>(b.length()) - length >= bOffset &&
53 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
54 [](unsigned char a, unsigned char b)
55 { return std::tolower(a) == std::tolower(b); });
58 bool isManagedAssembly(const std::string& fileName)
60 return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
61 iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
62 !isNativeImage(fileName);
65 bool isNativeImage(const std::string& fileName)
67 return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
70 bool cmdOptionExists(char** begin, char** end, const std::string& option)
72 return std::find(begin, end, option) != end;
75 std::string readSelfPath()
78 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
81 return std::string(buff);
87 std::string concatPath(const std::string& path1, const std::string& path2)
89 std::string path(path1);
90 if (path.back() == PATH_SEPARATOR) {
93 path += PATH_SEPARATOR;
100 void splitPath(const std::string& path, std::vector<std::string>& out)
102 std::istringstream ss(path);
105 while (std::getline(ss, token, ':')) {
106 out.push_back(token);
110 std::string absolutePath(const std::string& path)
113 char realPath[PATH_MAX];
114 if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
115 absPath.assign(realPath);
120 int getRootPath(std::string pkgId, std::string& rootPath)
126 if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
127 _ERR("Failed to get UID");
131 pkgmgrinfo_pkginfo_h handle;
133 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
134 if (ret != PMINFO_R_OK) {
138 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
139 if (ret != PMINFO_R_OK) {
144 ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
145 if (ret != PMINFO_R_OK) {
146 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
150 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
154 int getExecName(std::string pkgId, std::string& execName)
159 pkgmgrinfo_pkginfo_h pkg_handle;
160 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
161 if (ret != PMINFO_R_OK) {
164 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
165 if (ret != PMINFO_R_OK) {
166 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
170 pkgmgrinfo_appinfo_h app_handle;
171 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
172 if (ret != PMINFO_R_OK) {
173 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
176 ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
177 if (ret != PMINFO_R_OK) {
178 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
179 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
182 execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
184 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
185 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
189 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
194 pkgmgrinfo_pkginfo_h pkg_handle;
195 int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
196 if (ret != PMINFO_R_OK) {
199 ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
200 if (ret != PMINFO_R_OK) {
201 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
205 pkgmgrinfo_appinfo_h app_handle;
206 ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
207 if (ret != PMINFO_R_OK) {
208 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
211 ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
212 if (ret != PMINFO_R_OK) {
213 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
214 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
215 //Does not return error because the metadata key may not exist.
218 metadataValue = std::string(value);
220 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
221 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
225 std::string baseName(const std::string& path)
227 auto pos = path.find_last_of(PATH_SEPARATOR);
228 if (pos != std::string::npos)
229 return path.substr(0, pos);
231 return std::string(".");
235 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
237 std::string result = str;
238 std::string::size_type pos = 0;
239 std::string::size_type offset = 0;
241 while ((pos = result.find(pattern, offset)) != std::string::npos) {
242 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
243 offset = pos + replace.size();
249 bool isFileExist(const std::string& path)
252 return stat(path.c_str(), &sb) == 0;
255 uintptr_t getFileSize(const std::string& path)
259 if (stat(path.c_str(), &sb) == 0) {
266 std::string stripNiDLL(const std::string& path)
268 std::string niPath(path);
269 if (path.size() < 5) return niPath;
270 if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
271 niPath = path.substr(0, path.size()-4);
272 else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
273 niPath = path.substr(0, path.size()-4);
275 if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
276 return niPath.substr(0, niPath.size()-3);
281 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
283 std::map<std::string, std::string> assemblyList;
284 std::map<std::string, std::string> tmpList;
286 auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
287 if (isManagedAssembly(path) || isNativeImage(path)) {
288 std::string dllName = stripNiDLL(name);
289 std::pair<std::map<std::string, std::string>::iterator, bool> ret;
290 ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
291 if (ret.second == false) {
292 if (isNativeImage(path))
293 tmpList[dllName] = path;
298 for (auto directory : directories) {
299 scanFilesInDir(directory.c_str(), reader, 1);
300 // merge scaned dll list to tpa list.
301 // if the dll is already exist in the list, that is skipped.
302 assemblyList.insert(tmpList.begin(), tmpList.end());
305 std::map<std::string, std::string>::iterator it;
306 for (it = assemblyList.begin(); it != assemblyList.end(); it++)
307 tpaList += it->second + ':';
309 if (tpaList.back() == ':')
313 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
316 struct dirent* entry;
319 if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
322 dir = opendir(directory.c_str());
327 std::vector<std::string> innerDirectories;
329 while ((entry = readdir(dir)) != nullptr) {
331 std::string path = concatPath(directory, entry->d_name);
332 switch (entry->d_type) {
340 if (stat(path.c_str(), &sb) == -1)
343 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
349 reader(path, entry->d_name);
350 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
351 innerDirectories.push_back(path);
355 for (auto& d : innerDirectories)
356 scanFilesInDir(d.c_str(), reader, depth - 1);
361 void updateAssemblyInfo(const std::string& getPath, const std::string& setPath, bool isSymlink)
367 // change smack label for symbolic link.
368 if (smack_lgetlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
369 if (smack_lsetlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
370 fprintf(stderr, "Fail to set smack label\n");
375 // change owner and groups for symbolic link.
376 if (!stat(getPath.c_str(), &info)) {
377 if (lchown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
378 fprintf(stderr, "Failed to change owner and group name\n");
381 // change smack label
382 if (smack_getlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
383 if (smack_setlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
384 fprintf(stderr, "Fail to set smack label\n");
389 // change owner and groups for generated ni file.
390 if (!stat(getPath.c_str(), &info)) {
391 if (chown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
392 fprintf(stderr, "Failed to change owner and group name\n");
397 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
398 int fd = open(path.c_str(), O_RDONLY);
400 _ERR("Can't open directory: %s", path.c_str());
403 int ret = fchown(fd, uid, gid);
406 _ERR("Failed to change owner of: %s", path.c_str());
412 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
413 bs::error_code error;
414 bf::permissions(path, permissions, error);
416 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
422 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
423 if (!setOwnership(path, uid, gid)) {
424 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
427 if (!setDirPermissions(path, permissions)) {
428 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
434 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
435 if (!bf::exists(path)) {
436 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
439 bf::perms permissions = bf::status(path).permissions();
441 if (stat(path.c_str(), &stats) != 0) {
444 if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
445 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
451 bool createDir(const bf::path& path) {
452 if (bf::exists(path)) {
455 bs::error_code error;
456 bf::create_directories(path, error);
458 _ERR("Failed to create directory: %s", error.message().c_str());
464 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
466 // Check whether the function call is valid
467 if (!bf::exists(path1) || !bf::is_directory(path1)) {
468 _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
471 if (!bf::exists(path2)) {
472 // Create the destination directory
473 if (!createDir(path2)) {
474 _ERR("Unable to create destination directory %s", path2.c_str());
477 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
478 copyOwnershipAndPermissions(path1, path2);
481 if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
482 _ERR("Destination directory %s already exists", path2.c_str());
485 if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
486 copyOwnershipAndPermissions(path1, path2);
489 } catch (const bf::filesystem_error& error) {
490 _ERR("Failed to copy directory: %s", error.what());
494 // Iterate through the source directory
495 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
497 bf::path current(file->path());
498 bf::path target = path2 / current.filename();
499 if (bf::is_symlink(symlink_status(current))) {
500 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
503 bs::error_code error;
504 bf::copy_symlink(current, target, error);
506 _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
509 } else if (bf::is_directory(current)) {
510 // Found directory: Recursion
511 if (!copyDir(current, target, flags)) {
515 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
518 bf::path destination = target;
519 if (flags & FS_COMMIT_COPY_FILE) {
520 destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
522 if (flags & FS_MERGE_OVERWRITE) {
523 bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
525 bf::copy_file(current, destination);
527 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
528 copyOwnershipAndPermissions(current, destination);
530 if (flags & FS_COMMIT_COPY_FILE) {
531 if (flags & FS_MERGE_OVERWRITE) {
534 bf::rename(destination, target);
537 } catch (const bf::filesystem_error& error) {
538 _ERR("Failed to copy directory: %s", error.what());
545 bool copyFile(const bf::path& path1, const bf::path& path2) {
546 bs::error_code error;
547 if (!bf::exists(path1)) {
550 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
552 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
558 bool moveFile(const bf::path& path1, const bf::path& path2) {
559 if (!bf::exists(path1) || bf::exists(path2)) {
562 bs::error_code error;
563 bf::rename(path1, path2, error);
565 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
566 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
568 _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
571 bf::remove_all(path1, error);
573 _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
580 bool removeFile(const bf::path& path) {
581 if (!bf::exists(path)) {
584 bs::error_code error;
585 bf::remove(path, error);
587 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
593 bool removeAll(const bf::path& path) {
597 bs::error_code error;
598 bf::remove_all(path, error);
600 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
606 static void SHA256(std::string path, char outputBuffer[65])
608 FILE *file = fopen(path.c_str(), "rb");
613 unsigned char hash[SHA256_DIGEST_LENGTH];
615 SHA256_Init(&sha256);
617 const int bufSize = 32768;
618 char *buffer = (char*)malloc(bufSize);
624 while ((bytesRead = fread(buffer, 1, bufSize, file))) {
625 SHA256_Update(&sha256, buffer, bytesRead);
627 SHA256_Final(hash, &sha256);
628 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
629 sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
631 outputBuffer[64] = 0;
637 std::vector<std::string> depsJsonParser(std::string pkgId, std::string rootPath, std::string execName, std::string tpaList, bool isTool, sqlite3 *tac_db)
639 std::vector<std::string> parserData;
640 std::string depsJsonName = execName.substr(0, execName.rfind(".dll")) + ".deps.json";
641 std::string depsJsonPath = concatPath(rootPath, depsJsonName);
642 std::string binPath = concatPath(rootPath, "bin");
643 if (bf::exists(depsJsonPath)) {
644 std::ifstream ifs(depsJsonPath);
645 Json::CharReaderBuilder reader;
649 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
650 _ERR("Failed to parse of deps.json");
654 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
655 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
656 for (auto& nuget : nugetPackages.getMemberNames()) {
657 if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) != NULL ||
658 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) != NULL ||
659 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) != NULL ||
660 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) != NULL) {
663 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
664 if (assemblies != Json::nullValue) {
665 const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
666 bool isDependency = false;
667 for (auto& dependency : dependencies.getMemberNames()) {
668 if (strstr(dependency.c_str(), TIZEN_DOTNET_NUGET) != NULL ||
669 strstr(dependency.c_str(), NET_STANDARD_LIBRARY_NUGET) != NULL) {
676 bool isExistTpaAssembly = false;
677 for (auto& assembly : assemblies.getMemberNames()) {
678 std::string assembly_name = assembly.substr(assembly.rfind('/') + 1);
679 if (strstr(replaceAll(tpaList, ".ni.dll", ".dll").c_str(), assembly_name.c_str()) != NULL) {
680 isExistTpaAssembly = true;
684 if (!isExistTpaAssembly) {
685 _INFO("Nuget : %s", nuget.c_str());
688 std::string name = nuget.substr(0, nuget.find('/'));
689 std::string version = nuget.substr(nuget.rfind('/') + 1);
690 std::string sql = "INSERT INTO TAC (PKGID, NUGET, NAME, VERSION) " \
691 "VALUES ('" + pkgId + "', '" + nuget + "', '" + name + "', '" + version + "');";
692 dbInsert(tac_db, TAC_APP_LIST_RESTORE_DB, sql);
693 parserData.push_back(concatPath(__TAC_DIR, name));
695 std::string nugetPath = concatPath(__TAC_DIR, nuget);
696 if (bf::exists(nugetPath)) {
697 for (auto& assembly : assemblies.getMemberNames()) {
698 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
699 std::string originPath = concatPath(nugetPath, assemblyName);
700 if (bf::exists(originPath)) {
701 parserData.push_back(originPath);
707 for (auto& assembly : assemblies.getMemberNames()) {
708 std::string assembly_name = assembly.substr(assembly.rfind('/') + 1);
709 char buffer[65] = {0};
710 SHA256(concatPath(binPath, assembly_name), buffer);
711 parserData.push_back(nuget + "/" + assembly_name + "/" + buffer);
712 _INFO("Assembly / SHA256 : %s / %s", assembly_name.c_str(), buffer);